Docker + Python (Flask)

server.py

from flask import Flask

# create a Flask app
app = Flask(__name__)

# define a route
@app.route('/', methods=['GET'])
def root():
    return "welcome to a flask application"

@app.route('/products', methods=['GET'])
def products():
    return [
        {"name": "product1", "price": 100}, 
        {"name": "product2", "price": 200},
        {"name": "product3", "price": 300},
        {"name": "product4", "price": 400},
        {"name": "product5", "price": 500}
    ]

# run the app
app.run(port=5000, host="0.0.0.0")

Dockerfile

# decide the base image
FROM python:alpine3.21

# set the working directory
WORKDIR /src

# copy the current directory contents into the container at /src
COPY . .

# install dependencies
RUN pip install flask

# expose the port
EXPOSE 5000

# command to run on container start
CMD ["python", "server.py"]

Commands:

1.create image
docker image build -t my_python_image .

docker image ls

2.create container
docker container run -itd --name my_python_container -p 5000:5000 my_python_image

docker container ls

docker container log

3.check status
curl localhost:5000

4.remove container

docker container rm –f my_python_container

5.remove image

docker image rm my_python_image

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.