Python Docker Container


Run a script

  1. Pull the image.
  2. 
    docker pull python:3.8.0-alpine3.10 
    # python:3.8-slim-buster
    # python:3.8
    docker image ls
        
  3. Run image.
  4. 
    docker container run --rm -it python:3.8.0-alpine3.10 
    # --rm remove after exit
    # -it enter after create
    docker container run --rm -it python:3.8.0-alpine3.10 python -V
    docker container run --rm -it python:3.8.0-alpine3.10 pip -V
    docker container run --rm -it python:3.8.0-alpine3.10 cat /etc/os-release
    # the ending is cmd in image
        
  5. Create script. main.py
  6. 
    import os
        
  7. Run script that has no dependency.
  8. 
    docker container run --rm -it 
        -v /path/to/folder:/workfolder:ro # read only
        python:3.8.0-alpine3.10 
        python /workfolder/main.py
        
  9. Need Dockerfile for build.
  10. 
    FROM python:3.8
    
    RUN pip3 install -r requirements.txt
    # RUN apt-get -y update (optional)
    RUN mkdir -p /workfolder
    COPY ./main.py /workfolder/
    CMD [ "python" , "/workfolder/main.py" ] # similar to subprocess
        
  11. Run image build based on Dockerfile.
  12. 
    docker image build -t goodpython:v01 .
    docker image ls
    docker container run --rm -it goodpython:v01 # repo:tag
        

Run a flask project

  1. After image is created, view in docker images
  2. 
    docker run -d -p 5000:5000 myimage
    curl http://localhost:5000
        
  3. 
        

References


  1. Containerized Python Development – Part 1
  2. Build your Python image
  3. 【Docker入门教学】搭建Python的环境(3.8) p.6
  4. Installing system packages in Docker with minimal bloat
  5. How To Build and Deploy a Flask Application Using Docker on Ubuntu 18.04
  6. Docker + Flask | Dockerizing a Python API
  7. Tensorflow Docker requirements
  8. Part 5 – Install TensorFlow 2.0 with GPU support on Ubuntu 18.04 using Docker