创建基于 Docker 的开发环境

目的: 构建一个可以运行 python 项目的容器。

构建容器

新建一个目录,比如 python_env,编辑 Dockfile, pip.conf, requirements.txt 三个文件。

pip.conf 是用来给 pip 配置镜像地址的。

[global]
index-url = <http://mirrors.aliyun.com/pypi/simple/>
[install]
trusted-host=mirrors.aliyun.com

requirements.txt 写需要安装的 python 依赖。

然后编辑 Dockerfile。

# MAINTAINER Laily <i@laily.net>
# Dockerizing Python: Dockerfile for building python env.
FROM python:2.7.10
MAINTAINER Laily <i@laily.net>
WORKDIR /usr/src/app
RUN apt-get install -y libssl-dev libcurl4-openssl-dev
COPY pip.conf /root/.pip/pip.conf
COPY requirements.txt /usr/src/app/requirements.txt
RUN pip install -r /usr/src/app/requirements.txt
# RUN apt-get install -y libjpeg8-dev
RUN pip install pillow==2.9.0
ENV QB_ENV stage
EXPOSE 8000
CMD ["bash"]

然后执行命令构建

docker build -t laily/python:0.1 .

可以查看已经构建好的容器

$ docker images
REPOSITORY                TAG           IMAGE ID                CREATED                SIZE
laily/python               0.1      8e265b757f00      4 weeks ago      766MB

配合 Docker-compose

docker-compose 安装

Mac 和 Windows 用户不需要单独安装 docker-compose,在安装桌面版 docker 的时候已经安装好了。

进入 https://github.com/docker/compose/releases 这个页面选择最新版的 docker-compose 下载安装即可。

为 zsh 添加自动补全

在 .zshrc 文件里加上 docker 和 docker-compose 即可。

plugins = (
    ...
    docker
    docker-compose 
)

创建 docker-compose.yml 文件

version: '3'
services:
  my_app:
    image: laily/python:0.1
    container_name: my_app
    ports:
      - 20001:8715
    volumes:
      - ~/work/my_app:/opt/my_app
    command: python /opt/my_app/server.py

然后使用 docker-compose up my_app 就可以使用我们的 docker python 环境启动本地 /work/my_app 的项目了。