如何自定义 Django Docker镜像?
2018-06-12 by dongnan
开始之前
某个 Python 项目,基于 Python:3.6 与 Django:1.11 框架开发,希望项目能够容器化,然后可以通过 docker-compose 等工具编排容器/应用,本篇文章的目标是自定义Django基础镜像。
与《为什么需要自定义一个基础镜像?》文章相同,基础镜像作用是为项目镜像提供支持。它构建在 Python 官方镜像之上,添加项目一些需要的扩展模块,例如 Django、pymysql、Gunicorn等常用模块,具体以项目实际需求为准。
最后为能够高效的处理静态文件请求,使用 Nginx 反向代理 Django 应用,不过这是下一篇文章要讲的了,《Django容器(下): 使用Gunicorn管理Django》,敬请期待 公众号每周四 docker专题更新文章。。
环境描述
容器镜像: python:3.6
容器系统: debian 9 (stretch)
Docker版本: CE - 17.06.0
Docker主机: Ubuntu Server 16.04
操作步骤
基础镜像目录
tree base/
base/
├── conf
│   ├── 404.html
│   ├── default.conf
│   ├── nginx.conf
│   ├── requirements.txt
│   ├── sources.list
│   ├── ssl
│   │   ├── domain.crt
│   │   └── domain.key
│   └── supervisord.conf
└── Dockerfile
2 directories, 9 files
基础镜像 Dockerfile
cat base/Dockerfile
# start-base
FROM python:3.6
MAINTAINER dongnan
# apt
COPY conf/sources.list /etc/apt/sources.list
RUN apt-get update \
    && apt-get install -y supervisor nginx \
    && apt-get clean \
    && rm -r /var/lib/apt/lists/*
# env
ENV TZ=Asia/Shanghai \
    LANG=en_US.UTF-8
# django
COPY conf/requirements.txt /root/
RUN pip --no-cache-dir install -r /root/requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
- 这个 Dockerfile很短,因为是项目基础镜像,只做一些基础工作就可以了。
- 它首先安装 supervisor nginx软件包,然后是设置容器的环境变量。
- 最后使用 pip安装项目依赖,django 、pymysql都在requirements.txt文件中定义。
构建镜像
docker build -t start-base .
Sending build context to Docker daemon    767kB
Step 1/8 : FROM python:3.6
# ...省略
Successfully built fc3f6f242301
Successfully tagged start-base
验证镜像
基础镜像准备完毕后,就可以在项目镜像使用了,这里没有为基础镜像添加 TAG 标记,所以它是默认的 latest 。
docker images
start-base latest
小结
最后来总结下文章中的知识点
- 基础镜像作用是为项目镜像提供支持,并在基础镜像之上添加项目代码,完成项目镜像构建。
- 使用 supervisor在容器中管理nginx、gunicorn (python WSGI Server)进程。
- pip是- python包管理工具,该工具提供了对- python包的查找、下载、安装等功能。
- pip -i选项, 指定仓库地址,默认为 https://pypi.org/simple,速度很慢建议使用国内仓库。