使用 Django
Python
Docker ComposeDjango/PostgreSQL

在一切工作开始前,需要先编辑好三个必要的文件。

Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
Dockerfile
requirements.txt
Django>=2.0,<3.0
psycopg2>=2.7,<3.0
docker-compose.yml
version: "3"
services:

  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: 'postgres'

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
docker-compose.yml
docker compose runDjango
$ docker compose run web django-admin startproject django_example .
Dockerfiledjango-admin startproject django_example
Django
$ ls
Dockerfile       docker-compose.yml          django_example       manage.py       requirements.txt

如果你的系统是 Linux,记得更改文件权限。

$ sudo chown -R $USER:$USER .
django_example/settings.pyDATABASES = ...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
        'PASSWORD': 'postgres',
    }
}
docker compose up
$ docker compose up

django_db_1 is up-to-date
Creating django_web_1 ...
Creating django_web_1 ... done
Attaching to django_db_1, django_web_1
db_1   | The files belonging to this database system will be owned by user "postgres".
db_1   | This user must also own the server process.
db_1   |
db_1   | The database cluster will be initialized with locale "en_US.utf8".
db_1   | The default database encoding has accordingly been set to "UTF8".
db_1   | The default text search configuration will be set to "english".

web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  |
web_1  | November 23, 2017 - 06:21:19
web_1  | Django version 1.11.7, using settings 'django_example.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.
Django8000127.0.0.1:8000Django
docker compose up
$ docker compose run web python manage.py syncdb