https://ianlondon.github.io/blog/deploy-flask-docker-nginx/

Install the prerequisites

Aftersshing into your server, update your packages, then install python, pip, git, and docker. Afterwards, use pip to install virtualenv.

sudo apt-get update
sudo apt-get install python-dev python-pip git docker.io
sudo pip install virtualenv

Watch that you installdocker.ioand notdocker, they’re different things!

install

1 .Set up a virtual environment in a directory called venv with the command virtualenv venv.

Activate the virtual environment with source venv/bin/activate.

2 . Make a file requirements.txt that has all your dependencies in it.

Install your dependencies with pip install -r requirements.txt

Make a flask app at app/main.py. For the Docker image we will use, you need to do two important things:

Make sure the app is really called main.py

Make sure the Flask app variable is really called app. The Flask app variable is declared like app = Flask(..blah blah..). If you call this variable something else like my_app = Flask(..blah blah..), the Docker image won’t find it and it will not work!

file tree

root_project_dir/

  Dockerfile

  requirements.txt

  app/
    main.py

  venv/

dockerfile

FROM tiangolo/uwsgi-nginx-flask:flask

# copy over our requirements.txt file
COPY requirements.txt /tmp/

# upgrade pip and install required python packages
RUN pip install -U pip
RUN pip install -r /tmp/requirements.txt

# copy over our app code
COPY ./app /app

# set an environmental variable, MESSAGE,
# which the app will use and display
ENV MESSAGE "hello from Docker"

main.py

from pyfiglet import Figlet
import os
from flask import Flask

app = Flask(__name__)

font = Figlet(font="starwars")

@app.route("/")
def main():
    # get the message from the environmental variable $MESSAGE
    # or fall back to the string "no message specified"
    message = os.getenv("MESSAGE", "no message specified")

    # render plain text nicely in HTML
    html_text = font.renderText(message)\
            .replace(" "," ")\
            .replace(">",">")\
            .replace("<","&lt;")\
            .replace("\n","<br>")

    # use a monospace font so everything lines up as expected
    return "<html><body style='font-family: mono;'>" + html_text + "</body></html>"

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

Build and run!

docker build -t flask_ascii .
docker run -p 80:80 -t flask_ascii

Using a different environmental variable

You can overwrite many of the commands specified in the Dockerfile, including the environment variables. To change the $MESSAGE var to something else, use the-eflag (for “Environment”):

docker run -p 80:80 -e MESSAGE="something else" -t flask_ascii

Daemonize it!

If everything’s working, run it as an auto-restarting daemon

docker run -d --restart=always -p 80:80 -v /root/webapp/app:/app -rm=true -t flask_ascii

results matching ""

    No results matching ""