Skip to content

Latest commit

 

History

History
118 lines (95 loc) · 2.86 KB

05.Create_Sample_VSCode.md

File metadata and controls

118 lines (95 loc) · 2.86 KB
title
Docker sample Container of Django with VSCode

Define the project components

  1. Create an empty project directory

  2. Create a new file called Dockerfile in your project directory.

  3. 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/
  4. Create a requirements.txt in your project directory

    Django==3.0.7
    psycopg2==2.8.4
  5. Create a pip.conf in your project directory

    [global]
    index-url = https://pypi.tuna.tsinghua.edu.cn/simple
    [install]
    trusted-host=mirrors.aliyun.com
  6. 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

Create a Django project

  1. Change to the root of your project directory
  2. Create the Django project by running the docker-compose run command as follows. docker-compose run web django-admin startproject composeexample .

Connect the database

  1. In your project directory, edit the composeexample/settings.py file.

  2. 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,
        }
    }
  3. Run the docker-compose up command from the top level directory for your project.
    docker-compose up

  4. http://localhost:8000

  5. List running containers.
    docker ps

  6. 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

dockerfile_best-practices
dev-best-practices