To use Docker Compose with Django, you will need to create a Dockerfile
and a docker-compose.yml
file.
Here is an example Dockerfile
that you can use as a starting point:
FROM python:3.8
ENV PYTHONUNBUFFERED 1
RUN mkdir /app
WORKDIR /app
COPY requirements.txt /app/
RUN pip install -r requirements.txt
COPY . /app/
This Dockerfile
starts from the official Python Docker image and installs the required Python packages from requirements.txt
. It then copies the rest of your Django project files into the container.
Next, you can create a docker-compose.yml
file to define the services that make up your app. Here is an example docker-compose.yml
file that you can use:
version: '3'
services:
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
db:
image: postgres:10
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
volumes:
- postgres_data:/var/lib/postgresql/data/
volumes:
postgres_data:
This file defines two services: web
and db
. The web
service is built from the Dockerfile
in the current directory and runs the Django development server on port 8000. The db service is a PostgreSQL database, which your Django app will use to store data.
To start your Django app with Docker Compose, run the following command:
$ docker-compose up
This will build the web
service and start both the web
and db
services. Your Django app will be available at http://localhost:8000.
If you make any changes to your Django code, you will need to rebuild the web
service for the changes to take effect. You can do this by running:
$ docker-compose build web
Thats all happy coding...
Top comments (0)