Build Docker From Scratch With PostgreSQL & Django app

Gerry Sabar
3 min readJul 25, 2019

Let’s create a directory in our app named docker-django, then create a directory inside it named djangoapp. Inside djangoapp folder create a file named Dockerfile with code as follow:

Followed by create a requirements.txt file for our django project as follow:

Next, install this file using this command:

$ pip install -r requirements.txt

We also need to create a bash file as our entry point to execute our django app in our docker later:

Next we’ll create the images from this Dockerfile (in Linux environment, maybe you need prefix sudo command). The command is (sudo) docker build . -t <your_image_name> for example my image name is djangoapp, therefore the command will be:

$ docker build . -t djangoapp

Great! Now we have developed our images & going to push to Docker repository. Let’s login to docker first:

$ docker login

Then provide your docker credential. After that let’s tag our docker image for our Docker repository. The basic syntax is:

docker tag <docker_image_in _local> <USERNAME>/<docker_image_in_repository>

For example my docker image in local is djangoapp and also going to use the same name in Docker repository so the command will be:

$ docker tag djangoapp gerrysabar/djangoapp

Now, let’s push it to our docker repository with basic syntax:

docker push <USERNAME>/<IMAGENAME>

Example of my work is as follow:

$ docker push gerrysabar/djangoapp

Please wait until it’s done. The process will take sometime as need to upload quite large file. After it’s done, let’s implement django in our docker. Inside djangoapp let’s create a django app with command (my app name is gerry)

$ django-admin startproject djangoapp gerry

Our directory structure should be like this:

Let’s run the docker for our test:

docker run -p 5000:5000 gerry

Great! now if you access localhost:5000 you can see something like this:

Congratulations! we have implemented Django inside our docker. Next we’ll create docker-compose.yml. This file will be used so whenever you need to modify your docker you don’t need to execute docker build repeatedly. For example we’re going to add PostgreSQL inside our docker now. Let’s create docker-compose.yml in the same directory with Dockerfile:

Let’s build our adjusted docker using docker-compose.yml now using this command:

$ docker-compose build --up

Congratulation! now you’ve developed docker from scratch and implemented Django & PostgreSQL inside it. You also can push your docker image again if you want to do so. If you want to deploy this to Digital Ocean you can read this article.

--

--

No responses yet