一、准备文件
tree ../djanjo-project/
../djanjo-project/
├── docker-compose.yml
├── Dockerfile
└── requirments.txt
1.1、Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirments.txt /code/
RUN pip install -r requirments.txt
COPY . /code/
1.2、requirments.txt
Django>=2.0,<3.0
psycopg2>=2.7,<3.0
1.3、docker-compose.yml
version: '3'
service:
db:
image: postgres
volumes:
- db_data: /var/lib/postgresql
environment:
POSTGRES_PASSWORD: 'postgresql'
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
volumes:
db_data: {}
1.4、生成配置文件
docker-compose run web django-admin startproject myexample .
二、修改myexample/settings.py
ALLOWED_HOSTS = ['*'] #允许访问的主机
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': 5432,
}
}
三、启动容器
docker-compose up -d
##查看日志
$ docker logs djanjo-project_db_1
2022-04-12 01:50:50.912 UTC [1] LOG: starting PostgreSQL 14.2 (Debian 14.2-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
2022-04-12 01:50:50.912 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
2022-04-12 01:50:50.912 UTC [1] LOG: listening on IPv6 address "::", port 5432
2022-04-12 01:50:50.927 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2022-04-12 01:50:50.953 UTC [59] LOG: database system was shut down at 2022-04-12 01:50:50 UTC
2022-04-12 01:50:50.967 UTC [1] LOG: database system is ready to accept connections
$ docker logs djanjo-project_web_1
You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
April 12, 2022 - 01:53:27
Django version 2.2.28, using settings 'myexample.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
访问浏览器 http://<ip>:8000