docker_practice/compose/django.md

121 lines
3.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 使 Django
> `Python`
使 `Docker Compose` `Django/PostgreSQL`
Docker `Dockerfile` Docker
```docker
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
```
使 Python `Dockerfile` [ Dockerfile 使](../image/dockerfile/README.md)
`requirements.txt`
```bash
Django>=2.0,<3.0
psycopg2>=2.7,<3.0
```
`docker-compose.yml` 西 web 使 Docker
```yaml
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` ](compose_file.md)
使 `docker-compose run` `Django`
```bash
$ docker-compose run web django-admin startproject django_example .
```
web 使 Compose 使 `Dockerfile` web 使 `django-admin startproject django_example`
`Django`
```bash
$ ls
Dockerfile docker-compose.yml django_example manage.py requirements.txt
```
Linux,
```bash
$ sudo chown -R $USER:$USER .
```
`django_example/settings.py` `DATABASES = ...`
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'HOST': 'db',
'PORT': 5432,
'PASSWORD': 'postgres',
}
}
```
[postgres](https://hub.docker.com/_/postgres/) 镜像固定设置好的。然后,运行 `docker-compose up`
```bash
$ 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.
```
`Django` Docker `8000` `127.0.0.1:8000` `Django`
Docker `docker-compose up`
```bash
$ docker-compose run web python manage.py syncdb
```