Docker or Python or Django?

Published at

April 18, 2022

Author

Erlend ter Maat


I wrote about how to create a django project on your local machine without python. It was useful. But it turned out that there are two very different ways to look at the question: How can Docker help to build a project from scratch?

We could 1. build a docker project running a django project. 2. or build a django project with docker project.

The first one I wrote about earlier. It is an evolving process in which the project gets more complete in time. The other way is about what building a django project using a docker fixed docker image would look like.

Input/Output

I’m not sure if docker has room for this use case in the form of regular command line options, but an environment variable would be sufficient in my humble opinion. We could provide a shell script to pass the variable to the image, start the image in a container and would clean up the temporal docker files afterwards.

In order to create a django project without having python on your system one would:

  1. Download the support script;

  2. That is gonna take a parameter and launch the image;

  3. that would put the new project in the current working directory.

This would be a more true meaning on how to build a django project from scratch with docker.

Helper script

#!/usr/bin/env bash

docker build . -t djangobuilder
docker run djangobuilder --name djangobuilder -e DOCKER_PROJECT_NAME=$1 DOCKER_PROJECT_DIR=$2
FROM python:3.10.4-slim

RUN pip install django

WORKDIR /var/www

CMD django-admin startproject $DOCKER_PROJECT_NAME $DOCKER_PROJECT_DIRECTORY

What goes wrong here?

I tried to make Docker solve a problem that it is not good at. Docker is about providing applications, not about generate project files. So, the image should provide python, not a django project. The container will provide the project files.

That makes the docker part easier and the helper script part more complex, but stil readable.

Helper script 2

#!/usr/bin/env bash

DOCKER_PROJECT_NAME=$1

echo "pip install django" > temp.sh
echo "django-admin startproject $DOCKER_PROJECT_NAME ./" >> temp.sh
echo "pip freeze > requirements.txt" >> temp.sh

# Host a generic python image with the current host dir in the remote /project dir
#   and launch the temporary script that contains instructions on how to build
#   the django project!
docker run -it -v $(pwd):/project -w /project python:3.10.4-slim bash /project/temp.sh

rm temp.sh

Conclusion

How can docker help to create a project from scratch? It provides a framework where one is able to select and use resources that your project needs, without changing the requirements of ones development machine. It also provides opportunities to build projects in such a fashion that it would increase the confidence of your most experienced co-workers and friends that the developer that uses Docker for everything, except making coffee, is far on it’s way of loosing contact with reality…