准备数据目录
- 数据库持久化存储卷目录:pg_data
- django项目管理目录:code
准备compose配置文档 docker-compose.yml
version: '3'
services:
db:
image: postgres
volumes:
- pg_data:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=P@ssw0rd
ports:
- "5432:5432"
web:
build: .
command: python3 manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
准备requirements.txt
Django>=1.8,<2.0
psycopg2
准备pip源配置文件 pip.conf
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
准备Dockerfile
FROM python:3.8
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY pip.conf /root/.pip/pip.conf
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
创建django项目
sudo docker-compose run web django-admin.py startproject project_test .
编辑 project_test/settings.py 配置数据库连接
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'P@ssw0rd'
'HOST': 'db',
'PORT': 5432,
}
}
使用docker-compose启动开发环境:
$ docker-compose up
djangosample_db_1 is up-to-date
Creating djangosample_web_1 ...
Creating djangosample_web_1 ... done
Attaching to djangosample_db_1, djangosample_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 | May 30, 2017 - 21:44:49
web_1 | Django version 1.11.1, using settings 'composeexample.settings'
web_1 | Starting development server at http://0.0.0.0:8000/
web_1 | Quit the server with CONTROL-C.
安装完毕