Home > Software engineering >  Dockerize a Flaskapp - Python
Dockerize a Flaskapp - Python

Time:06-29

I need help Dockerizing an app.

Following is my requirements.txt:

Flask==0.12
flask-redis==0.3

And this is my app.py:

import os

from flask import Flask
from flask_redis import FlaskRedis

app = Flask(__name__)
app.config['REDIS_URL'] = 'redis://redis:6379/0'

redis = FlaskRedis(app)

@app.route('/')
def counter():
    return '{0} {1} {2}'.format('This webpage has been viewed',str(redis.incr('web2_counter')),' time(s).')

I've created my Dockerfile like this:

FROM python:3.6-stretch

# We don't want to run our application as root if it is not strictly necessary, even in a container.
# Create a user and a group called 'app' to run the processes.
# A system user is sufficient and we do not need a home.
RUN adduser --system --group --no-create-home app


# Place the application components in a dir below the root dir
COPY . /app

# Make the directory the working directory for subsequent commands
WORKDIR /app


# Install from the requirements.txt we copied above
RUN pip install -r requirements.txt --no-cache-dir


# Hand everything over to the 'app' user
RUN chown -R app:app /app


# Subsequent commands, either in this Dockerfile or in a
# docker-compose.yml, will run as user 'app'
USER app

COPY . .

and my docker-compose.yml:

version: '3'

services:

  web:
     build: .
     command: flask run --host=0.0.0.0 --port=5000
     ports:
        - "5000:5000"
     environment:
      - FLASK_APP=app.py
      - FLASK_DEBUG=1
     volumes:
        - .:/app
     depends_on:
        - redis

  redis:
    image: "redis:alpine"
    ports:
      - '6379:6379'

The redis container starts as normal, but not the web. Getting below error:

"Traceback (most recent call last):
  File "/usr/local/bin/flask", line 5, in <module>
    from flask.cli import main
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/flask/__init__.py", line 19, in <module>
    from jinja2 import Markup, escape
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ImportError: cannot import name 'Markup' from 'jinja2' (/usr/local/lib/python3.11/site-packages/jinja2/__init__.py)"

Expected result: curl localhost:5000

This webpage has been viewed N time(s)

Can someone point me to the right direction?

CodePudding user response:

Your requirements.txt should contain all needed requirements. Something like this

Flask==1.1.1
Jinja2==2.11.3
MarkupSafe==2.0.1
itsdangerous==1.1.0
Werkzeug==2.0.2
flask-redis==0.3
  • Related