我无法弄清楚部署一个使用uwsgi / gunicorn的Django项目的“正确”方式(我还没有决定使用什么,可能uwsgi,因为它有更好的性能,build议?)和nginx使用泊坞窗。
我看到有些人把所有东西放在同一个容器里。 我不是docker专家,但是容器应该只做一件事情。 所以,Django + nginx似乎是2而不是1。
现在,我的部署思路是:
有没有其他办法可以做到这一点? 有一个教程,涵盖了这个案件更深入一点。 我需要一个坚实的生产,而不仅仅是testing我的电脑上的一些代码。
我目前正在按照你想要的方式构build一个django应用程序。
我使用docker-compose来做到这一点。 这是我的docker-compose.yml
version: '2' services: nginx: container_name: nginx-container links: - uwsgi build: ./nginx ports: - "8888:80" volumes_from: - uwsgi uwsgi: container_name: uwsgi-container build: ./uwsgi expose: - "8001" volumes: - ./code/conf:/opt/conf - ./code/app:/opt/app
Dockerfile for uWSGI:
FROM python:3.5 RUN ["pip", "install", "uwsgi"] CMD ["uwsgi", "--master", "--ini", "/opt/conf/uwsgi.ini"]
Dockerfile for nginx:
FROM nginx RUN ["rm", "/etc/nginx/conf.d/default.conf"] RUN ["ln", "-s", "/opt/conf/nginx.conf", "/etc/nginx/conf.d/"] CMD ["nginx", "-g", "daemon off;"]
这是我的目录树:
├── README.md ├── code │ ├── app │ └── conf ├── collectstatic.sh ├── docker-compose.yml ├── install.sh ├── migrate.sh ├── nginx │ └── Dockerfile ├── restart.sh ├── upgrade.sh ├── uwsgi │ └── Dockerfile
所以我用docker-compose build构build我的图像,然后用docker-compose up -d在后台启动新的容器,然后我可以执行一些设置任务,比如安装django,生成密钥或者任何你想让你的容器准备好的东西。
nginx和uwsgi容器使用共享卷读取configuration文件并与文件套接字进行通信。
那么,不知道这是最好的方法,但这是一个正在进行的工作。
我从Michael Hamptonfind了这个答案:
“只有当进程位于同一台主机,虚拟机或容器中时才能正常工作,因为它试图连接到同一台机器,当它们位于不同的容器中时,它不起作用。
你需要改变你的nginxconfiguration,以便它使用uwsgi容器的内部IP地址。“
如果你将Nginx放在不同的容器中,你必须牢记这一点,你也必须设置nginx.conf,将静态文件目录指向别名,以防止安全问题。
我希望这个代码适用于每个人,花了我几个小时来了解如何编写Gunicorn,docker和Nginx:
# nginx.conf upstream djangoA { server $DOCKER_CONTAINER_SERVICE:9000 max_fails=3 fail_timeout=0; # In my case looks like: web:9000 } Server { include mime.types; # The port your site will be served on listen 80; # the domain name it will serve for server_name $YOUR_SERVER_NAME;# substitute your machine's IP address or FQDN charset utf-8; #Max upload size client_max_body_size 512M; # adjust to taste location /site_media { alias $DIRECTORY_STATIC_FILES/site_media;#your Django project's media files have to be inside of the container have nginxs, you can copy them with volumes. expires 30d; } location / { try_files $uri @proxy_to_app; } # Finally, send all non-media requests to the Django server. location @proxy_to_app { proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_set_header Host $host; proxy_pass http://djangoA; } }
对于docker工人来说:
#production.yml version: '2' services: db: extends: file: base.yml service: db nginx: image: nginx:latest volumes: - ./nginx:/etc/nginx/conf.d/ - ./$STATIC_FILE_ROOT/site_media:/$STATIC_FILE_ROOT/site_media ports: - "80:80" depends_on: - web web: extends: file: base.yml service: web build: args: - DJANGO_ENV=production command: bash -c "python manage.py collectstatic --noinput && chmod 775 -R project/site_media/static && gunicorn project.wsgi:application" volumes: - ./$DIRECTORY_APP:/$DIRECTORY_APP ports: - "9000:9000" depends_on: - db volumes: db_data: external: true