Docker-compose之部署Django
阿新 • • 發佈:2022-01-25
Docker-compose 部署Django
1.Web
1,Create an empty project directory.
[root@docker: ~]#mkdir Django_Compose_Dir
2,Create a new file called Dockerfile
in your project directory.
[root@docker: Django_Compose_Dir]#cat Dockerfile # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/
3,Create a requirements.txt
in your project directory.
[root@docker: Django_Compose_Dir]#cat requirements.txt
Django>=3.0,<4.0
psycopg2>=2.8
4,Create a file called docker-compose.yml
in your project directory
[root@docker: Django_Compose_Dir]#cat docker-compose.yml version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: /bin/bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db
5,Change to the root of your project directory and Create the Django project by running the docker-compose run command as follows.
[root@docker: Django_Compose_Dir]#docker-compose run web django-admin startproject composeexample .
6、After the docker-compose
command completes, list the contents of your project.
[root@docker: Django_Compose_Dir]#ll
total 20
drwxr-xr-x 3 root root 108 Jan 25 18:03 composeexample
drwxr-xr-x 3 root root 16 Jan 25 17:22 data
-rw-r--r-- 1 root root 612 Jan 25 17:20 docker-compose.yml
-rw-r--r-- 1 root root 190 Jan 25 17:19 Dockerfile
-rwxr-xr-x 1 root root 670 Jan 25 17:22 manage.py
-rw-r--r-- 1 root root 31 Jan 25 17:21 requirements.txt
-rw-r--r-- 1 root root 337 Jan 25 17:21 settings.py
7、則建立的 django-admin 檔案屬於 root 使用者。這是因為容器作為根使用者執行。更改新檔案的所有權。
[root@docker: Django_Compose_Dir]# sudo chown -R $USER:$USER .
2、DB
1.在專案目錄中,編輯 composeexample/settings.py 檔案。
[root@docker: Django_Compose_Dir]#cat composeexample/settings.py
# settings.py
import os
ALLOWED_HOSTS = ["*"]
[...]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('POSTGRES_NAME'),
'USER': os.environ.get('POSTGRES_USER'),
'PASSWORD': os.environ.get('POSTGRES_PASSWORD'),
'HOST': 'db',
'PORT': 5432,
}
2.從專案的頂級目錄執行 docker-compose up 命令。
[root@docker: Django_Compose_Dir]#docker-compose up