Django and Docker example
This is my example Django setup using Docker for local development.
It's taken me a while to piece the Docker stuff together and I'm definitely not confident that it's ideal. But, so far, it seems to work.
Many of the notes below are so I don't forget anything; some might be useful to others too.
Install Docker, e.g. Docker for Mac.
Download this repository.
.envfile within your copy that contains these lines:
# Environment settings for local development. ALLOWED_HOSTS=* DATABASE_URL=postgres://postgres@db:5432/postgres DJANGO_SECRET_KEY=ChangeThisForALiveSite DJANGO_SETTINGS_MODULE=config.settings.local
On the command line, within this directory, do this to build the image and start the container:
Open http://0.0.0.0:8000 in your browser.
That might work...?
Dockerfile describes an image, which will be our web server.
It keeps this directory synced with the
/app/ directory in our web container.
It installs Pipenv and then our
project's python requirements from the
docker-compose.yml describes the two services: the web and postgres servers.
It loads the environment variables we set in the
The web server will run the Django
migrate command and then
The very small example Django project is in
myproject/, with its settings and
URL conf in
You can run the Django tests within the running web container by doing this:
docker-compose exec web ./scripts/run-tests.sh
That will run the included shell script that, in turn, runs Django's
manage.py test command, and runs
coverage, generating a report in the,
command line output, and in the
htmlcov/ directory it will create.
Run other Django management commands, e.g.:
docker-compose exec web ./manage.py createsuperuser
Or get a bash prompt within the web container:
docker-compose exec web bash
Stop it all running:
If you change something in
docker-compose.yml then you'll need to build
Or, just for the
docker-compose build web
Update python requirements with pipenv
I'm not sure the best way to do this, so here's what I've done when wanting to update a pipenv requirement:
On my local machine (not in the Docker container) create a pipenv and install requirements:
Make any updates to requirements, e.g.:
pipenv update Django
That should update
Delete this pipenv virtualenv:
Re-build the Docker
webcontainer, which will take noticed of the
docker-compose stopfirst if it's currently running):
docker-compose build web
Keeping Docker tidy
It seems easy to end up with loads of unused images, containers and volumes, all taking up disk space.
List all images:
docker images -a
docker rmi IMAGE_ID IMAGE_ID
List running containers:
List containers that aren't running:
docker ps -a -f status=exited
docker rm CONTAINER_ID CONTAINER_ID
docker volume ls
docker volume rm VOLUME_NAME VOLUME_NAME
List volumes not connected to any containers:
docker volume ls -f dangling=true
Delete those unconnected volumes:
docker volume prune