跳转至

如何使用 Docker-Compose 部署 Django 项目?


2019-01-03 by dongnan

环境

项目结构

tree -L 2 star/

star/
├── docker-compose.yml
├── images
│   ├── base
│   ├── Dockerfile
│   └── starStar

文件作用

  • docker-compose.yml 用于容器编排。
  • Dockerfile 用于创建项目的应用镜像。
  • base 目录,用于创建基础镜像,django依赖:python、gunicorn、nginx、supervisor等。
  • starStar 目录,项目git 仓库 。

配置文件

docker-compose

cat star/docker-compose.yml

version: '2'
services:

  star-web:
    build: images/
    volumes:
      - /etc/localtime:/etc/localtime
      - www-data:/var/www/html/
      - log-data:/var/log/
    ports:
      - 443:443

volumes:
    www-data:
      driver: local
    log-data:
      driver: local

Dockerfile 文件

cat star/images/Dockerfile

FROM star-base
# author see star-base
# apt see star-base
# env see star-base

# nginx
COPY base/conf/nginx.conf /etc/nginx/nginx.conf
COPY base/conf/default.conf /etc/nginx/conf.d/default.conf
COPY base/conf/ssl /etc/nginx/ssl

# django
# setting see star-base
COPY starStar/star /star
WORKDIR /star
RUN python manage.py collectstatic -l --noinput

# supervisor
COPY base/conf/supervisord.conf /etc/supervisor/supervisord.conf
CMD ["/usr/bin/supervisord","-c","/etc/supervisor/supervisord.conf"]

基础镜像

目录结构

tree star/images/base/

star/images/base/
├── conf
│   ├── default.conf
│   ├── nginx.conf
│   ├── requirements.txt
│   ├── sources.list
│   ├── ssl
│   │   ├── domain.crt
│   │   └── domain.key
│   └── supervisord.conf
└── Dockerfile

supervisor 配置文件

cat star/images/base/conf/supervisord.conf

[supervisord]
nodaemon=true
pidfile=/var/run/supervisord.pid
logfile=/var/log/supervisor/supervisord.log

[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"

[program:gunicorn]
command=gunicorn --bind unix:/var/run/django.socket star.wsgi:application --log-level=debug
stderr_logfile=/var/log/gunicorn.stderr
stdout_logfile=/var/log/gunicorn.stdout

使用

代码上线,代码推送到远程 git仓库后,使用下面的命令 build最新的镜像,并创建新的容器。

docker-compose up -d --build

命令参数

docker-compose up -h
Builds, (re)creates, starts, and attaches to containers for a service.
# ...省略
Usage: up [options] [--scale SERVICE=NUM...] [SERVICE...]
Options:
    -d                         Detached mode: Run containers in the background,
                               print new container names. Incompatible with
                               --abort-on-container-exit and --timeout.
    --build                    Build images before starting containers. 

生产环境

生产环境,从安全角度务必设置 DEBUGFalse ,另外 ALLOWED_HOSTS 设置为你自己的域名,例如:

DEBUG = False
ALLOWED_HOSTS = ['your_ip','www.demo.com']

此外关于静态文件(包括上传的附件),需要调整的参数类似如下:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# media
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/attachments/'

最后 Dockerfile 已经定义了静态文件收集命令 python manage.py collectstatic -l --noinput

参考

如何在容器中使用 Nginx & Gunicorn 管理Django 应用?

回到页面顶部