Run Python Application with Docker
You can run a Python script using Docker containers. This tutorial will help you to run a Python script over command line within Docker isolated environment.
Run Python Example within Docker
- Create Python Script – First, create a sample Python script to run on web server under the Docker container. Edit script.py in your favorite text editor.
Add the following content:Python12print("Welcome to Tecadmin.net");print("This is Python running in Docker");
- Create Dockerfile – Next create a file named Dockerfile under the same directory. Edit Dockerfile in a text editor:
Add below content to file.
FROM python:3 WORKDIR /usr/src/app ## Un-comment below lines to install dependencies #COPY requirements.txt ./ #RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD [ "python", "./script.py" ]
Here you can choose your preferred Python version and operating systems for your Docker container.
- Build Image – You have a Dockerfile and a sample script.py Python script in your current directory. Now, you need to create a docker image with these files. Execute below command to build and crate Docker image.
docker build -t img-python-example .
The above command will create a Docker image with name img-python-example.
- Run Container –Now, you have a docker image now. Use this docker image to launch a new container on your system. To run your Docker container using the newly created image, type:
docker run --rm -it img-python-example
You can use “-d” option to run as demon mode.