Dockerize any application in minutes

How to dockerize any application easily

ContainersvsVMs_Image-1.webp

Getting Started

To develop with Python and Docker, first ensure that Python v3.7.13+ is installed on your machine. Downloadable packages are available at Python.org :

You’ll also need three additional tools before starting:

  1. The latest version of Docker Desktop, for either Windows or macOS (Intel or Apple-Silicon processor).
  2. Your preferred code editor (In my case, VSCode)

Virtual environment (Easy to manage depedencies)

Install virtualenv on your system

pip install virtualenv

Now create folder for your project and open code there

Create and activate virtual environment

virtualenv env && source venv/bin/activate

Freeze the requirements for your application

pip freeze > requirements.txt

Here, I have created a simple requests application with bs4 for google search of docker keyword

Dockerfile

Now, create file named Dockerfile in working directory

Let's start with Dockerfile

  • Search for appropriate docker image

    Choosing a small image is a smart choice in most cases, many can do the same work going from full-fledge Ubuntu:latest to minimal alpine:latest

Here, since we require basic python functionality along, with some pip depedencies so, python:<version>-alpine would be a fine choice for this dockerized application.

Using python:3.8-alpine as BaseImage.

Add this into Dockerfile to use python-alpine image as base

FROM python:3.8-alpine

Screenshot 2022-08-18 at 9.31.10 PM.png

  • Library Installation and Understanding Your Dockerfile

    Enter the following command to install pip depedencies, using our requirements.txt:
    RUN pip install -r requirements.txt
    
    Lastly, you’ll enter the command that Docker will execute once your container has started:
CMD [“python”, “main.py”] 
# You can enter the name for your file and different parameters.

You final Dockerfile should look something like below:

FROM python:3.8-alpine

# Create a directory for the project
WORKDIR /app
# Copy the project file to the container
COPY . .

# Install requirements
RUN pip install -r requirements.txt

CMD ["python", "main.py"]

This is one of the simplest examples of Dockerfile. Your Dockerfile can be more complex depending upon your application complexity.

Refer Docker docs for more.

Final Stage

Building the custom docker image

docker build -t image_name .

Screenshot 2022-08-18 at 9.43.21 PM.png

2
Subscribe to my newsletter

Read articles from Khushiyant Chauhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Khushiyant Chauhan
Khushiyant Chauhan