title |
---|
Docker sample Container of Django with VSCode |
-
Create an empty project directory
-
Create a new file called Dockerfile in your project directory.
-
Add the following content to the Dockerfile
# Save and close the Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY pip.conf /etc/pip.conf COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/
-
Create a requirements.txt in your project directory
Django==3.0.7 psycopg2==2.8.4
-
Create a pip.conf in your project directory
[global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple [install] trusted-host=mirrors.aliyun.com
-
Create a docker-compose.yml in your project directory
version: '3' services: web: # build: . 执行 根目录下 dockerfile build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres
- Change to the root of your project directory
- Create the Django project by running the docker-compose run command as follows.
docker-compose run web django-admin startproject composeexample .
-
In your project directory, edit the
composeexample/settings.py
file. -
Replace the DATABASES = ... with the following:
# setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } }
-
Run the docker-compose up command from the top level directory for your project.
docker-compose up
-
List running containers.
docker ps
-
Shut down services and clean up by using either of these methods:
-
停止应用键入
Ctrl-C
Gracefully stopping... (press Ctrl+C again to force) Killing test_web_1 ... done Killing test_db_1 ... done
-
run docker-compose down
$ docker-compose down Stopping django_web_1 ... done Stopping django_db_1 ... done Removing django_web_1 ... done Removing django_web_run_1 ... done Removing django_db_1 ... done Removing network django_default
-