Vscode + Docker + Nginx + Tomcat でhelloworld
DockerにてNginxとTomcatを構築。
Nginxはリバースプロキシサーバー、 Tomcatはアプリケーションサーバーとしてhelloworldを表示させる
今回はNginxコンテナとTomcatコンテナ、二つ作成する
前提条件
Vscode上で作成
Dockerが使える環境が必要です
install 確認コマンド
docker version
構成
docker-compose build
前の段階では以下の構成となります
. ├── docker-compose.yml ├── nginx │ ├── Dockerfile │ └── conf.d │ └── nginx.conf └── tomcat └── Dockerfile
最終的な構成となります。
. ├── docker-compose.yml ├── nginx │ ├── Dockerfile │ ├── conf.d │ │ └── nginx.conf │ └── log │ ├── access.log │ ├── error.log │ ├── tomcat_access.log │ └── tomcat_error.log └── tomcat ├── Dockerfile ├── log │ ├── catalina.2021-09-06.log │ ├── host-manager.2021-09-06.log │ ├── localhost.2021-09-06.log │ ├── localhost_access_log.2021-09-06.txt │ └── manager.2021-09-06.log └── webapps └── sample └── helloworld.html
必要なファイル
- docker-compose.yml
- Dockerfile(nginx)
- nginx.conf(nginx)
- Dockerfile(tomcat)
docker-compose.yml
services: nginx: build: context: ./nginx volumes: - ./nginx/conf.d:/etc/nginx/conf.d/ - ./nginx/log:/var/log/nginx ports: - 80:80 tomcat: build: context: ./tomcat volumes: - ./tomcat/webapps:/usr/local/tomcat/webapps - ./tomcat/log:/usr/local/tomcat/logs ports: - 8080:8080
リバースプロキシの設定用にconf.dを修正する必要があるため、マウントしておきます。
ログも何かと必要となるため、マウント。
webapps配下はアプリケーションのデプロイ場所となるためこちらも同様
dockerfile(nginx)
FROM nginx RUN apt-get update && apt-get install -y vim EXPOSE 80 RUN rm -rf /etc/nginx/conf.d/ COPY ./conf.d/nginx.conf /etc/nginx/conf.d/
- defaultのnginx設定を削除して作成した設定に入れ替える
RUN rm -rf /etc/nginx/conf.d/ COPY ./conf.d/nginx.conf /etc/nginx/conf.d/
nginx.conf
server { listen 80; server_name localhost; access_log /var/log/nginx/tomcat_access.log; error_log /var/log/nginx/tomcat_error.log; location / { proxy_pass http://host.docker.internal:8080; } }
- リバースプロキシの設定
http://localhost:80(nginx)でリクエストした場合に、
http://localhost:8080(tomcat)にリクエストを転送するようにする
dockerの場合はlocalhost
ではなくhost.docker.internal
でないと読み込んでくれないため、注意。
めちゃハマりました。
proxy_pass http://host.docker.internal:8080;
Dockerfile(tomcat)
FROM tomcat:9.0.52 RUN apt-get update && apt-get install -y vim EXPOSE 8080
versionはデプロイしたいアプリに合わせると良い。
今回はhelloworldを表示させたいだけ、なので気にしなくても良いが、こちらを使用
RUN apt-get update && apt-get install -y vim
何かしらのエラーがあった場合、設定を確認していく必要があるため、vimを入れておきます
vimにはだいぶ助けられました
手順
* image作成
docker-compose build
* コンテナ起動
docker-compose up -d
* http:localhost:80にアクセス
何もデプロイするものがないため404 not foundが返却されているが
tomcatの表示がされている。
http://localhost:80(nginx)にアクセスするとnginx.confで設定したproxy_pass
http://localhost:8080(tomcat)に転送されていることの確認ができました
マウントしたログで確認しても良い
* webapps直下にhelloworld.htmlを設置する
webapps/sample/helloworld.html
helloworld.html
<h1>helloworld</h1>
* コンテナを作り直して起動する
停止と削除
docker-compose down
構築
docker-compose build
起動
docker-compose up -d
* http:localhost:80/helloworld.htmlにアクセスする
無事に表示できました!!
コンテナ内の設定を確認したい場合は以下のコマンドでコンテナ内に入り、vimで確認していきましょう
docker-compose exec tomcat bash
GitHub
https://github.com/TakushiTokuyama/Docker/tree/develop/ReverseProxyServer