DEV Community

Carlos Armando Marcano Vargas
Carlos Armando Marcano Vargas

Posted on • Originally published at carlosmv.hashnode.dev on

Dockerizing a Django Application | Python.

In this article, we will build a container for a Django Application with Sqlite3 as a database using Docker. We are not going to build a Django Application from scratch. We will use a sample for this article.

You can clone the Django app from this repository.

Requirements

  • Docker installed

  • Git installed.

Dockerfile

FROM python:3.11

RUN mkdir /code
WORKDIR /code
RUN pip install --upgrade pip
COPY requirements.txt /code/

RUN pip install -r requirements.txt
COPY . /code/

EXPOSE 8000

CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

Enter fullscreen mode Exit fullscreen mode

Here we write the instructions Docker needs to build our image.

Building the image.

In the directory where is located the dockerfile, we run this command in our terminal.

docker build -t django-authentication .

Enter fullscreen mode Exit fullscreen mode

The docker build command uses the Dockerfile to create a new container image.

As the Docker documentation says, the -t flag tags your image. Since we named the image django-authentication, we can refer to that image when we run a container.

The . at the end of the docker build command tells Docker that it should look for the Dockerfile in the current directory.

Running the container

docker run -dp 8000:8000 django-authentication

Enter fullscreen mode Exit fullscreen mode

We use the -d flag to run the new container in detached mode (in the background). We also use the -p flag to create a mapping between the hosts port 8000 to the containers port 8000. Without the port mapping, you wouldnt be able to access the application

After a few seconds, we will be able to go to localhost:8000/home/ and see this page:

Conclusion

First time I dockerize a Django application. It wasn't hard, the docker documentation offers helpful samples to use. This application uses Sqlite3 as a database, so using a container was enough. But if we want to use Postgres as a database, we have to use Compose, because we have to build a container for Postgres, and Compose is used for building and running multi-containers docker applications.

Thank you for taking the time to read this article.

If you have any recommendations about other packages, architectures, how to improve my code, my English, or anything; please leave a comment or contact me through Twitter, or LinkedIn.

References

Top comments (0)