nginx と pythonのbottleを別コンテナで構築したかった。
そこでdocker-composeで複数のコンテナを作成した。
利用する技術
- python3
- bottle
- uwsgi
- nginx
- docker
利用するファイルとディレクトリ階層
/mysystem
docker-compose.yml
/myapp
Dockerfile
uwsgi.ini
app.py
/web
Dockerfile
nginx.conf
index.html
myapp/app.py
from bottle import route, run, default_app
@route('/test')
def test():
return 'test success'
if __name__ == '__main__':
run(host='0.0.0.0', port=3031, debug=True, reloader=True)
else:
application = default_app()
hostの部分はdockerに外部からアクセスするには'0.0.0.0'
と指定する。
default_app()は先頭でbottleからimportする。
myapp/uwsgi.ini
uwsgiの設定ファイル
[uwsgi]
master = true
wsgi-file = app.py
socket = :3031
max-requests = 5000
logto = uwsgi.log
myapp/Dockerfile
Pythonアプリケーション用のDockerfile
From python:3
RUN pip install --upgrade pip
RUN pip install bottle
RUN pip install uwsgi
COPY app.py /opt/myapp
COPY uwsgi.ini /opt/myapp
web/nginx.conf
nginxの設定ファイル
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
#include /etc/nginx/conf.d/*.conf;
upstream uwsgi {
server uwsgi:3031;
}
server {
listen 80;
charset utf-8;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /test {
uwsgi_pass uwsgi;
include uwsgi_params;
}
}
}
include /etc/nginx/conf.d/*.conf;
の部分をコメントアウトし、upstream uwsgi
以下を追記した。
もちろんdefault.confなどを/etc/nginx/conf.d/に配置して利用してもOK。
web/Dockerfile
nginx用のDockerfile
FROM nginx
COPY index.html /usr/share/nginx/html
docker-compose.yml
複数のDockerfileをまとめて処理できる。
version: '2'
services:
uwsgi:
container_name: myapp
build: ./myapp
command: uwsgi --ini uwsgi.ini
nginx:
container_name: myweb
build: ./web
links:
- uwsgi
volumes_from:
- uwsgi
ports:
- "0.0.0.0:80:80"
コンテナ作成と実行
dockerコンテナ作成
docker-compose.ymlがあるディレクトリで以下のコマンド
docker-compose build
dockerコンテナ起動
docker-compose up
バックグラウンド実行なら
docker-compose up -d
dockerコンテナ停止
docker-compose down
stop + rmしてくれる
備考
さくらのVPSにdocker-composeがinstallされてなかったので以下を参照してinstallした。
https://docs.docker.com/compose/install/
実行権限が必要なので以下を参照して権限付与した。
https://qiita.com/DQNEO/items/da5df074c48b012152ee