This guide will show you how to install Django inside Docker with docker-compose and without installing any dependencies on the host system. Since there are a few quirks and I have to look it up myself every damn time, here's a guide hopefully helping me and other the next time.
This guide will:
- help you install the newest version of django inside your docker container
- be independent of your host OS and python version, so you can always get the newest version inside docker
- provide a basic setup of django inside docker with docker-compose to build upon
Basic requirements file
Start with a requirements.txt file containing only:
Save it as
Firstly, a Dockerfile is needed to set up and run our project.
We'll use a basic version you can expand later.
It uses Python 3.8, installs all dependencies from your
and then copies your project files into the image.
So copy this in your
FROM python:3.8 WORKDIR /code # copy and install requirements first # -> speeds up build if requirements haven't changed COPY requirements.txt /code/ RUN pip install -r requirements.txt # copy rest of files # (not needed since we also mount a volume, # but you won't mount in production) COPY . /code/
version: '3' services: web: build: . volumes: - .:/code/ command: bash tty: True ports: # external is the port you use on your host, i.e. localhost:8000 # internal is the port django uses inside the container # format: external:internal - "8000:8000"
Running it all
After having set up the above files, run the following steps:
docker-compose buildto build the images.
docker-compose upto start the container, leave it running.
docker-compose exec web pip freeze > requirements.txtto pin the installed dependencies to their actual version.
requirements.txtshould now contain version numbers.
docker-compose exec web django-admin startproject YOURNAME .(mind the dot!) to start a new django project in the current directory.
sudo chown -R $USER ./to own the docker-generated files. Otherwise you'll get file permission problems when working with the generated files on your host (outside of docker).
docker-compose exec web python ./manage.py runserver 0.0.0.0:8000.
You should now be able to access a congratulations page at
If you're interested in setting up Django for production, feel free to check out my guide on how to set up Django deployment for production for the same stack.
Note: Changing ports
If you want to change the port to access your Django application,
you only have to change the external port, i.e. the
So to switch to port 80, change the line below
ports: - "80:8000"
Then the container can be accessed with
localhost:80 or just
localhost (as 80 is the default).