首页 > 解决方案 > How to install Django+Postgres on Docker using base image Alpine:3.14

问题描述

Following are the initial three files that you will need to create in your project folder

Dockerfile

# syntax=docker/dockerfile:1
FROM alpine:3.14
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN apk update
RUN apk add postgresql-dev
RUN apk add gcc
RUN apk add python3-dev
RUN apk add musl-dev
RUN apk add py3-pip
RUN pip install psycopg2
RUN pip install -r requirements.txt
COPY . /code/

docker-compose.yml

version: "3.9"
   
services:
  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
  web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

requirements.txt

Django>=3.0,<4.0
psycopg2-binary>=2.8

After creating the above 3 files run the following command:

docker-compose run web django-admin startproject example_project .

Next you will have to modify the settings for database in the newly created settings.py file in your django project folder. settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

Run:

docker-compose up

As the server is running go to the Terminal of your container and do migrations (Docker Desktop > Container/Apps > Expand docker > Docker_web CLI)

python3 manage.py migrate

标签: djangopostgresqldockerwindows-subsystem-for-linuxalpine

解决方案


Quick Notes: Before proceeding with the Docker installation, I installed WSL using the following documentation: https://docs.microsoft.com/en-us/windows/wsl/install-win10

Then I downloaded the Alpine Linux from the following link: https://github.com/yuk7/AlpineWSL

Download Link is as follows: https://github.com/yuk7/AlpineWSL/releases/tag/3.14.0-1

Then I set this Alpine to version 2 You can check the version the images are set to by using wsl -l -v You can set the version to 2 using wsl --set-version Alpine 2

Useful commands:

1] To rebuild the docker image after making changes to Dockerfile use:

docker build .

推荐阅读