Click here to Skip to main content
15,867,704 members
Articles / Containers / Docker
Tip/Trick

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 19.1K   9   2
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 Main.py File

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

Python
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()
@app.post("/insert_posts/")
async def create_item(userpost: UserPost):
    data = {‘post_id’: len(db.all()) + 1, ‘text’: userpost.text, 
            ‘likes’: userpost.likes, "user":userpost.user}
    db.insert(data)
    return {"status" : "Inserted", "data": data}
@app.get("/get_post")
def get_post():
    """
    Get all of the elements present in the database
    """
    return {"data": db.all()}
@app.get("/")
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:
    Docker
    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:
    Docker
    CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Create an Image from this Docker File

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

    Docker
    "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.

History

  • 31st January, 2022: Initial version

License

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


Written By
InvoZone
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 
This looks like a good first start to an article but there are a few commands and a bit of information that is wrong. Article needs to be reviewed and corrected. As someone who has used Docker for years I would not recommend this article.
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.