Set Up Docker Python

Requirements:
Install Python and Docker

Create folder on computer named docker-python and follow steps below:

cd /path/to/python-docker 
pip3 install Flask 
pip3 freeze | grep Flask >> requirements.txt 

Create app.py file and add this code

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, Docker!'

Create a Dockerfile for Python

# syntax=docker/dockerfile:1

FROM python:3.8-slim-buster

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

Directory structure is now:

python-docker
|____ app.py
|____ requirements.txt
|____ Dockerfile

Build an image:

docker build --tag docker-python .

Run your image as a container with ability to open in browser

docker run --publish 5000:5000 docker-python

Test in terminal to see if works

curl localhost:5000
Hello, Docker!

Check Docker Desktop and you should see it listed as a running container with ability to open in browser!

Leave a Reply

Your email address will not be published.