Docker-compose之部署Django

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
posted @ 2022-01-25 18:34  Carol-z  阅读(190)  评论(0编辑  收藏  举报