Deploying flask app to Docker - routing/redirect issues

Viewed 635

I have a flask app that works perfecting on my computer and also hosted on a cloud service, however after 'containerizing' it with docker every POST request results in the same message and then the app GETs the previous page - no redirect to the appropriate page. Here is one line of the output:

172.24.0.1 - - [19/Sep/2018:17:12:31 +0000] "POST /login HTTP/1.1" 302 209 "http://127.0.0.1:5000/login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"

Here is the Dockerfile:

FROM ubuntu:16.04

#set container enviroment variables
ENV FLASK_APP app.py

#apt-get and system utilities
RUN apt-get update && apt-get install -y\
    curl apt-utils apt-transport-https debconf-utils gcc build-essential g++5\
    && rm -rf /var/lib/apt/lists/*

#python libraries
RUN apt-get update && apt-get install -y\
    python3-pip python3-dev python3-setuptools \
    --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*

#install necessary locales
RUN apt-get update && apt-get install -y locales \
    && echo "en_US.UTF-8 UTF-8" > /etc/locale.gen \
    && locale-gen

#copy flask app module
COPY app app
COPY gunicorn_config.py requirements.txt ./

#install packages
RUN pip3 install --upgrade pip
RUN pip3 install -r requirements.txt

#expose application port
EXPOSE 5000
CMD ["gunicorn", "--config", "gunicorn_config.py", "app.app:app"]

The docker-compose.yml:

version: '3'
services:
  plain_app:
    image: plainapp:1.1.0
    ports:
      - 5000:5000
    working_dir: /app
    command: ["gunicorn", "--config", "../gunicorn_config.py", "app:app"]

Here is my project struture:

-project_home
  - app
  Dockerfile
  docker-compose.yml
  requirements.txt
  gunicorn_config.py

gunicorn_config.py:

bind = '0.0.0.0:5000'
workers = 2
accesslog = '-'
loglevel = 'development'
capture_output = True
enable_stdio_inheritance = True

Thank you for your input.

1 Answers

I know exactly how you were feeling mate :D Had the same problem with Flask serving a React.js app today...

It was functioning well on my PC and on the server, bus as soon as I created an image (on the same server, with the same files) the static files couldn't be loaded and were redirected with the 392 HTTP answer.

The key to solve this was, to change the paths.

Before:

  • template_folder = ".../html"
  • static_folder = ".../html/static"

After:

  • template_folder = ".../html"
  • static_folder = ".../html"
  • static_url_path = "/static"

Somehow you can't use static_files in Docker. You have to tell the client to search for static files in the main directory and add "static" as a prefix. It searches in the same folder as it would do with static_folder = ".../html/static" but somehow Docker can't use this method. So you'll have to do the trick with the url path...

Related