Dockerize any application in minutes
How to dockerize any application easily
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 :
- For Windows: download Python
- For macOS: download Python
- For Linux/UNIX: download Python
You’ll also need three additional tools before starting:
- The latest version of Docker Desktop, for either Windows or macOS (Intel or Apple-Silicon processor).
- 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 ofdocker
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 minimalalpine: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
Library Installation and Understanding Your Dockerfile
Enter the following command to installpip
depedencies, using ourrequirements.txt
:
Lastly, you’ll enter the command that Docker will execute once your container has started:RUN pip install -r requirements.txt
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 .
Subscribe to my newsletter
Read articles from Khushiyant Chauhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by