Today I will show you how to set up a really simple Django development environment directly on the Docker container without a local Django installation. We will also run a PostgreSQL server in a docker container.
I am assuming that you have already installed Docker and Docker-compose. If not, there are pretty goods docs on docker's official website. Follow them to install on your OS (Windows/macOS/Linux). I am using macOS, but others will be almost similar (if you find it difficult, just put a comment below).
Follow the below steps to quick start Django development on the Docker environment
1) Make a project directory, e.g.-TestApp
2) Create a file name Dockerfile on the directory and add the following lines
FROM python:3.9.1
LABEL maintainer="roni@wiseturn.net"
LABEL vendor="wiseturn.net"
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY required-package.txt /code/
RUN pip install -r required-package.txt
COPY . /code/
3) Create a file name required-package.txt and add the following lines -
Django>=3.2,<4.0
psycopg2>=2.8
4) Then create a file name docker-compose.yml and add the following lines -
version: "3.9"
services:
db:
image: postgres
volumes:
- ./container-data/db:/var/lib/postgresql/data
environment:
- POSTGRES_NAME=postgres
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
web:
build: .
command: 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) Now open the terminal ad go to the project directory, and enter the following command to start a Django project -
$ docker-compose run web django-admin startproject testapp .
6) All required files and folders are generated by this time. Go to testapp folder , open settings.py file add
import os
on top of the page and replace
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
with
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,
}
}
7) Now, to run the containers, execute the following commands -
$ docker-compose down
$ docker-compose build
$ docker-compose up -d
8) Now open your browser and go http://localhost:8000; you will see the Django welcome page.
This tutorial is for a quick start; next, I will post explaining these and how to do it for the professional app.