Dockerfile for Python Application
1 min read

Dockerfile for Python Application

Learn to create a Dockerfile for a python application.

What is Dockerfile

A Dockerfile is used to create a docker image. The Dockerfile contains all the commands that can be executed on command line to build an image. It's just a group of all commands that gets executed all together.

There are some common steps that are required to build an images for an application.

Point a base image

To build a Dockerfile for python application, a python base image should pointed. In the below example I have used python 3.9.7 image. There are different flavors of a python image like python:<version>, python:<version>-slim, python:<version>-alpine and python:<version>-windowsservercore.

FROM python:3.9.7

Create application directory

The base image comes with some directories but always create your application directory. Create an application folder using below command.

RUN mkdir -p /home/app

Set root directory

Set the root directory where all the commands gets executed without telling the path. It should be absolute path.

WORKDIR /home/app

Copy source code

Now the source code from your local directory should be copied to the application directory created inside the Dockerfile.

COPY ./src/. /home/app/

Install dependencies

Install all python module dependencies. Python dependencies can be defined in requirements.txt file like package.json file. Use the below command to install all python dependencies.

RUN pip install --no-cache-dir -r requirements.txt

Command to init the application

A command the inits the application should be defined and that should run when the docker image runs. The CMD instruction is used to define such commands.

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

Complete Dockerfile

Here is the complete Dockerfile.

FROM python:3.9.7

LABEL maintainer="Onkar <onkar@gmail.com>"

RUN mkdir -p /home/app

WORKDIR /home/app

COPY ./src/. /home/app/
RUN pip install --no-cache-dir -r requirements.txt

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

Once you create a Dockerfile, put that file in the root of your application.

Create Image

The docker build command is used to create a build. The below command will create a python application image (python_app_image) that your can run.

docker build -t python_app_image .

Run a Dockerfile

The docker run command is used to run a docker image. The below command will run the python image as container and the application will be accessible on 8000 port on localhost.

docker run -p 8000:8000 python_app