Jump to content

Docker/Flask

From Wikiversity

Dockerfile

[edit | edit source]
# Configures a Flask web server and copies the current folder content
# to use as app root.

# Use the following commands to build and run the server.
#   docker build -t flask-server .
#   docker run -d -p 5000:5000 --name=flask-server flask-server

# Then open a web browser and connect to http://localhost:5000 .

# References:
#   https://code.visualstudio.com/docs/containers/quickstart-python
#   https://aka.ms/vscode-docker-python
#   https://runnable.com/docker/python/dockerize-your-flask-application
#   https://docs.docker.com/develop/develop-images/dockerfile_best-practices/

FROM python:alpine
RUN python -m pip install flask

WORKDIR /usr/src/app
COPY . .

EXPOSE 5000

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

app.py

[edit | edit source]
# Displays "Hello world!"
#
# References:
#   https://en.wikiversity.org/wiki/Flask/Hello_World

import flask

app = flask.Flask(__name__)

@app.route('/')
def root():
    return "Hello world!"

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

Try It

[edit | edit source]

Online Free

[edit | edit source]
  1. Use Play with Docker. Create an account and/or log in.
  2. Start an interactive session and add a new instance.
  3. In the terminal window, enter the following commands:
    • touch Dockerfile
    • touch app.py
  4. Use the Editor button to edit both files and save the contents above into each respective file.
  5. Run the following commands:
    • docker build -t flask-server .
    • docker run -d -p 5000:5000 --name=flask-server flask-server
  6. In the top window, select the 5000 button to connect to the running server.

On Your Own System

[edit | edit source]
  1. Install Docker Desktop or the Docker Engine.
  2. Save the files above into a new Docker Flask folder:
    • Dockerfile
    • app.py
  3. At a command prompt, change to the Docker Flask folder and then run the following commands:
    • docker build -t flask-server .
    • docker run -d -p 5000:5000 --name=flask-server flask-server
  4. Open a web browser to connect to the running server:

See Also

[edit | edit source]