Create Python Flask Docker Container
Create a folder and change to the folder
1 2 |
mkdir python-flask cd python-flask |
Create file
1 |
vi Dockerfile |
Add following content
1 2 3 4 5 6 7 8 9 10 |
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.
1 |
echo "Flask" > requirments.txt |
Now lets create our Python Flask Application
1 |
vi app.py |
Add following content
1 2 3 4 5 6 7 8 9 10 11 12 |
from flask import Flask import os import socket app = Flask(__name__) @app.route("/") def hello(): return "<h1>Ok, World</h1>" if __name__ == "__main__": app.run(host="0.0.0.0", port=8080) |
To test Flask application locally, install Flask using pip
1 |
sudo pip install Flask |
Now run the application using
1 |
python app.py |
Now you will be able to see web application at
1 |
http://localhost:8080 |
Press CTRL+C to stop the application.
To build Docker image, run
1 |
docker build -t python-flask-app . |
-t specify tag.
If all worked properly, you will see
You can see the container image listed
1 |
docker images |
Now your docker image is ready. To build a container using this image, run
1 |
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
1 |
http://localhost:8080 |
To stop the application, run
1 |
docker stop my-flask-app |
To start it, run
1 |
docker start my-flask-app |