開始之前
某個 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 --format "{{.Repository}} {{.Tag}}"
start-base latest
小結
最後來總結下文章中的知識點
- 基礎鏡像作用是爲
項目鏡像
提供支持,並在基礎鏡像之上添加項目代碼,完成項目鏡像構建工作。 - 使用
supervisor
在容器中管理nginx、gunicorn (python WSGI Server)
進程。 pip
是python
包管理工具,該工具提供了對python
包的查找、下載、安裝、卸載的功能。pip -i
選項, 指定倉庫地址,默認爲 https://pypi.org/simple,**速度很慢**建議使用國內倉庫。
參考文章
doker&k8s Qun [703906133]