Click here to Skip to main content
15,614,138 members
Articles / Containers / Docker
Posted 31 Jan 2022

Tagged as


9 bookmarked

How to Create an Image in Docker using Python

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
31 Jan 2022CPOL5 min read
This blog is about creating an image in Docker using Python.
The article comprises the docker introduction, reasons for its popularity, and layers of docker architecture. You will also learn how to create an image in Docker using Python Language.

Developers get frustrated when they develop a product that works flawlessly on their systems but does not respond well when run on the clients’ computer. It further gets frustrating when the same software clashes often between server computers and other computers.

Development experts considered this thing seriously and made a permanent solution to this problem. They have made “Docker” to solve this problem. dotCloud invented Docker in 2013. Most people face some challenges while creating an image in Docker using Python language. So, I have explained the complete procedure in this blog post.

You will learn some important commands of Docker and how to upload your Docker image in the dockerhub. Before digging into the topic straightaway, let’s start with the basic introduction of Docker.

What Is Docker?

To keep this introduction simple, it is a container where you can put your entire code and can deliver your package to the clients. Basically, it is a set of the platform as a software (PaaS) product that uses a Virtual Operating system.

All the containers have their own code, libraries, and features. The entire code is fully protected in a shell and can’t be mixed with other containers. But they can communicate easily through different communication channels.

Reasons for Docker’s Popularity

There are two major reasons Docker is helpful in development:

  • Docker is used to vanish the production errors of a project. It also reduces the errors on the development side.
  • You can easily increase and decrease the scalability of a project according to the project size and users.

Layers of Docker

  • Hardware

    It is the layer of the computer system that is mainly based on computer infrastructure.

  • Host Operating System

    The Host Operating System is the layer of the operating system of the developer that performs all the functionality.

  • Docker

    It is the layer that connects the whole code and connects it to the other clients’ computers. Basically, it redirects the host URL toward the client URL.

What Problems You Face When You Scale-up Your Project

Usually, you make the applications according to your needs and requirements. After some time, when your users grow or shrink, you want to scale up and scale down your app as needed. If you don’t change the scalability of your app, your resources will be wasted.

Solution of this Problem

To solve the issues related to scalability, a computer scientist discovered Kubernetes which helps in increasing and decreasing the scalability of the app according to the app's traffic.

Container Image

  • In a virtual environment, we make a txt file where all the dependencies are listed.
    pip freeze > requirements.txt

As you can see, there are many requirements available in the above image. This file will contain each and every command and library you are using in the project. For instance, if you use Tinydb rather than any database, it will include the name of Tinydb with its versions used in the project.

Create a File

The main file of Python is included in the virtual environment. It will include the following syntax:

from typing import Optional
from tinydb import TinyDB, Query
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
db = TinyDB(‘db.json’)
class UserPost(BaseModel):
    text: str
    likes: Optional[str] = 0
    user: str
app = FastAPI()"/insert_posts/")
async def create_item(userpost: UserPost):
    data = {‘post_id’: len(db.all()) + 1, ‘text’: userpost.text, 
            ‘likes’: userpost.likes, "user":userpost.user}
    return {"status" : "Inserted", "data": data}
def get_post():
    Get all of the elements present in the database
    return {"data": db.all()}
def hello_world():
    return {"Hello": "World"}

In the above program, I have explained how to print hello world using Docker in Python. In the start, I have used different libraries that reduce the code complexity. For instance, I have used Basemodel and Tinydb to fetch the database. The purpose of these libraries is to get all the pre-defined features of a function.

First, you create a Docker file:

In this Docker file, the following things are defined:

  • It is telling us about the language and version of the language in the first line.
  • In the second line, all the work directory is going in the code folder and the code folder is in the app project.
  • After that, it copies all the requirements from the requirements.txt file and places them into the code directory.
  • To run the code, the following command is used:
    RUN pip install --no-cache-dir -r /code/requirements.txt
  • Then, it copies all the Docker container code and is placed into the code directory.
  • Then, the final step is to run this command:
    CMD ["uvicorn", "main:app", "--host", "", "--port", "8000"]

Create an Image from this Docker File

  • First, you can extract/see all the images from the docker container:
    "docker images"
  • After that, you should make a docker image from the images file and assign a name to it:
    "docker build <image_name>"
  • Make a docker container from the following command:
    "docker run -d -p 8000:8000 <image_name>"
  • You can use the following command to check the running containers:
    "docker ps"
  • You can go in the running container while using this command:
    "docker exec -it bash"
  • The following command will be used to stop the container:
    "docker stop <container id>"
  • To see the status of all the docker containers:
    "docker ls -a"
  • If you don’t want to remove the container, you can do this as well:
    "docker remove <container id>"

It is very important to log into the docker in the terminal. If you don’t do this, this will create an error and will not show anything. You can log into the docker in the terminal through the following commands.

  • Docker login
  • Username
  • Password

How to Upload a Docker Image in Dockerhub

When you make an image in the docker, you have to upload the image in the dockerhub. There are some steps to be followed:

  • First, you need to make an account on the dockerhub.
  • You should create a repository in the dockerhub account.

  • You have to change the image name according to the repository name used in the dockerhub.
  • When you are going to push the image into the repository, you have to write the following command:
    "docker push <image_name>
  • If you are trying to take a pull of all the images in the repository, write the following command:

    "docker pull <image_name>

All your images will be shown in your dockerhub repository. You can take the pull and push the images through the terminal.


  • 31st January, 2022: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
United States United States
Eric is a highly motivated person with exceptional skills and expertise in Content writing, copywriting, and related fields. Eric is also a Blockchain and IT Professional with diverse expertise in Digital Marketing and Content Writing. Eric helps tech startups, businesses, and brands to grow with the demand they need in the digital age. Eric has worked with leading companies and individual CEOs by writing well-researched articles, blog posts, social media product/services descriptions, and eBooks published online. Eric is always willing to work and collaborate for a great opportunity!

Comments and Discussions

BugArticle needs some proof reading Pin
Member 149986928-Feb-22 2:46
Member 149986928-Feb-22 2:46 
QuestionMessage Closed Pin
4-Feb-22 5:29
deeksha arya4-Feb-22 5:29 
Questionvery useful but... Pin
znbn3-Feb-22 6:09
znbn3-Feb-22 6:09 
GeneralMessage Closed Pin
31-Jan-22 22:10
ASHISH GLADWIN31-Jan-22 22:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.