Create Python Flask Docker Container

Create a folder and change to the folder

mkdir python-flask
cd python-flask

Create file

vi Dockerfile

Add following content

FROM python:2.7-slim

WORKDIR /app
COPY . /app

RUN pip install -r requirements.txt

EXPOSE 8080

CMD ["python", "app.py"]

Create file requirements.txt, add “Flask” to it.

echo "Flask" > requirments.txt

Now lets create our Python Flask Application

vi app.py

Add following content

from flask import Flask
import os
import socket

app = Flask(__name__)

@app.route("/")
def hello():
	return  "

Ok, World

" if __name__ == "__main__": app.run(host="0.0.0.0", port=8080)

To test Flask application locally, install Flask using pip

sudo pip install Flask

Now run the application using

python app.py

Now you will be able to see web application at

http://localhost:8080

Press CTRL+C to stop the application.

To build Docker image, run

docker build -t python-flask-app .

-t specify tag.

If all worked properly, you will see

You can see the container image listed

docker images

Now your docker image is ready. To build a container using this image, run

docker container run -d --name my-flask-app -p 8080:8080 python-flask-app

You can access your python application running inside docker container on URL

http://localhost:8080

To stop the application, run

docker stop my-flask-app

To start it, run

docker start my-flask-app

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *