1. Home
  2. Docker
  3. Docker Examples
  4. Docker Python Example

Docker Python Example

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

  1. 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.
    nano script.py
    

    Add the following content:

  2. Create Dockerfile – Next create a file named Dockerfile under the same directory. Edit Dockerfile in a text editor:
    nano Dockerfile
    

    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.

  3. 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.

  4. 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.

Tags , ,
Was this article helpful to you? Yes No
Advertisement