how to run gunicorn on docker

Viewed 70698

I have 2 files that depend on each other when docker is start up. 1 is a flask file and one is a file with a few functions. When docker starts, only the functions file will be executed but it imports flask variables from the flask file. Example:

Flaskfile

import flask
from flask import Flask, request
import json

_flask = Flask(__name__)

@_flask.route('/', methods = ['POST'])
def flask_main():
    s = str(request.form['abc'])
    ind = global_fn_main(param1,param2,param3)
    return ind

def run(fn_main):
    global global_fn_main
    global_fn_main = fn_main
    _flask.run(debug = False, port = 8080, host = '0.0.0.0', threaded = True)

Main File

import flaskfile
#a few functions then
if__name__ == '__main__':
    flaskfile.run(main_fn)

The script runs fine without need a gunicorn.

Dockerfile

  FROM python-flask
  ADD *.py *.pyc /code/
  ADD requirements.txt /code/
  WORKDIR /code
  EXPOSE 8080
  CMD ["python","main_file.py"]

In the Command line: i usally do: docker run -it -p 8080:8080 my_image_name and then docker will start and listen.

Now to use gunicorn: I tried to modify my CMD parameter in the dockerfile to

["gunicorn", "-w", "20", "-b", "127.0.0.1:8083", "main_file:flaskfile"]

but it just keeps exiting. Am i not writing the docker gunicorn command right?

6 Answers

After struggling with this issue over the last 3 days, I found that all you need to do is to bind to the non-routable meta-address 0.0.0.0 rather than the loopback IP 127.0.0.1:

CMD ["gunicorn" , "--bind", "0.0.0.0:8000", "app:app"]

And don't forget to expose the port, one option to do that is to use EXPOSE in your Dockerfile:

EXPOSE 8000

Now:

docker build -t test .

Finally you can run:

docker run -d -p 8000:8000 test

This work for me:

FROM docker.io/python:3.7

WORKDIR /app

COPY requirements.txt ./

RUN pip install --no-cache-dir -r requirements.txt

ENV GUNICORN_CMD_ARGS="--bind=0.0.0.0 --chdir=./src/"
COPY . .

EXPOSE 8000

CMD [ "gunicorn", "app:app" ]

I was trying to run a flask app as well. I found out that you can just use

ENTRYPOINT['gunicorn', '-b', ':8080', 'app:APP']

This will take take the file you have specified and run on the docker instance. Also, don't forget the shebang on the top, #!/usr/bin/env python if you are running the Debug LOG-LEVEL.

gunicorn main:app --workers 4 --bind :3000 --access-logfile '-'

Related