Django is a high-level Python Web framework that enables rapid development of secure and maintainable websites. Docker is an open-source platform that automates the deployment, scaling, and management of applications using containerization. Together, they can be a powerful combination, especially in terms of consistent development environments and simplification of deployment management.
1. Installation – First, you need to install Docker and Docker Compose. Select your operating system, Download Docker Desktop and follow the instructions (https://docs.docker.com/docker-for-windows/install/).
1. Setup Dockerfile – Create a new file named Dockerfile in your project root directory. A Dockerfile is a text document that contains all the commands to assemble a Docker image for your Django application. An example of a Dockerfile content would look like:
\`\`\` FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ \`\`\`1. Setup Docker Compose – Docker Compose is a tool for defining and running multi-container Docker applications. Create a docker-compose.yml file in your project directory.
\`\`\` version: ‘3’services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: – .:/code ports: – “8000:8000“ depends\_on: – db \`\`\`
This Compose file defines two services, `db` and `web`. The `db` service uses the `postgres` image from the Docker Hub, while the `web` service builds a Docker image using the Dockerfile in the current directory.
1. Build the project – You can now bring the project up by running `docker-compose up`.
1. Create a Django project – If you don’t already have a Django project, you’ll need to create one with this command: `docker-compose run web django-admin startproject mysite .` replace `mysite` with your project name.
1. Connect Django with Postgres – Lastly, you need to update `DATABASES` configuration in Django settings file like below:
\`\`\` DATABASES = { ‘default’: { ‘ENGINE’: ‘django.db.backends.postgresql’, ‘NAME’: ‘postgres’, ‘USER’: ‘postgres’, ‘HOST’: ‘db’, ‘PORT’: 5432, } } \`\`\`1. Migrate & Create superuser – Run `docker-compose run web python manage.py migrate` to apply migrations. Then, `docker-compose run web python manage.py createsuperuser` to create a superuser for Django’s administrative interface.
1. Test – If everything was done correctly, you should be able to view your application by browsing to http://localhost:8000.
Remember that for the production environment, more configurations should be considered such as Docker Swarm or Kubernetes for orchestration, and it’s good to explore more about Django and Docker documentation for more advanced stuff.
Sources:
1. https://docs.docker.com/
2. https://www.djangoproject.com/
3. https://docs.docker.com/compose/django/
4. https://docs.djangoproject.com/en/3.2/intro/tutorial02/