Docker flask - jinja2.exceptions.TemplateNotFound:

2019-08-18 04:08发布

问题:

New to docker and trying to run a flask mysql app but getting a jinja2.exceptions.TemplateNotFound: index.html . No errors if I run python app.py outside of docker

Directory structure

  -docker-compose.yml
  -app
    -templates
          -index.html
    -app.py
    -Dockerfile
    -requirements.txt
  -db
    -init.sql

docker-compose.yml

version: "2"
services:
  app:
    build: ./app
    links:
      - db
    ports:
      - "5000:5000"

  db:
    image: mysql:5.7
    ports:
      - "32000:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - ./db:/docker-entrypoint-initdb.d/:ro

Dockerfile

FROM python:3.6

EXPOSE 5000

WORKDIR /app

COPY requirements.txt /app
RUN pip install -r requirements.txt

ENV IN_DOCKER_CONTAINER Yes

COPY app.py /app
CMD python app.py

requirements.txt:

Flask==1.0.2
Jinja2==2.10
gunicorn==19.6.0
flask-mysql

part of my app.py:

@app.route('/')
def index():
    conn = mysql.connect()
    cursor = conn.cursor()
    try:
        query = '''SELECT * from favorite_colors'''
        cursor.execute(query)
        data = cursor.fetchall()
    except Exception as e:
        return str(e)
    finally:
        cursor.close()
        conn.close()
    return render_template('index.html', MyExampleVar=str(data))

回答1:

Your Dockerfile only copies requirements.txt and app.py into the image. In order for the dockerized app.py to have access to templates and its contents, you need to copy templates as well by adding the line:

COPY templates /app/