前置条件

docker已安装好,可参考https://docs.docker.com/compose/install/https://docs.docker.com/engine/install/ubuntu/

Django项目

创建虚拟环境

打开终端,执行下面命令(我是在Linux下面进行的操作,Docker On Window碰到了docker启动的问题)

mkdir IdiotInspect
cd IdiotInspect
pipenv install django==3 gunicorn --python 3.6
pipenv shell

创建项目

django-admin startproject IdiotInspect .

做数据库迁移

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

更新配置文件settings.py

# DEBUG can be True/False or 1/0
DEBUG = int(os.environ.get('DEBUG', default=1))

创建环境文件.env

DEBUG=1

测试Gunicorn

gunicorn IdiotInspect.wsgi:application --bind 0.0.0.0:8000

Docker File, Image, Container

创建Dockerfile

$ cd path/to/your/dev/folder
$ cd IdiotInspect
$ touch Dockerfile
$ ls
Dockerfile

Dockerfile文件如下

# Base Image
FROM python:3.6
# create and set working directory
RUN mkdir /app
WORKDIR /app

# Add current directory code to working directory
ADD . /app/

# set default environment variables
ENV PYTHONUNBUFFERED 1
ENV LANG C.UTF-8
ENV DEBIAN_FRONTEND=noninteractive

# set project environment variables
# grab these via Python's os.environ
# these are 100% optional here
ENV PORT=8000

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
        tzdata \
        python3-setuptools \
        python3-pip \
        python3-dev \
        python3-venv \
        git \
        && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# install environment dependencies
RUN pip3 install --upgrade pip
RUN pip3 install pipenv

# Install project dependencies
RUN pipenv install --skip-lock --system --dev

EXPOSE 8888

CMD gunicorn IdiotInspect.wsgi:application --bind 0.0.0.0:$PORT

构建docker image

$ docker build -t idiot-inspect-on-docker -f Dockerfile .

运行容器

$ docker run -it -p 80:8000 idiot-inspect-on-docker

现在打开http://localhost就可以访问了, 端口就是使用80端口(映射到主机的端口)

80:8000表示容器端口8000,映射到主机端口80. 还没有搞明白这个EXPOSE端口的作用,原文命令是80:8888

查看container详情

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
35b781181802 beb52e9b60ea "/bin/sh -c 'gunicor…" 3 days ago Up 3 days 8888/tcp, 0.0.0.0:80->8000/tcp exciting_feistel

清理

列出在运行的容器

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
35b781181802 beb52e9b60ea "/bin/sh -c 'gunicor…" 31 minutes ago Up 30 minutes 8888/tcp, 0.0.0.0:80->8000/tcp exciting_feistel

停止容器

docker stop 35b781181802

修改docker内容

进入运行中的docker

sudo docker exec -it 35b781181802 bash

修改完成了执行docker commit命令

参考文档