skip to Main Content

I have Flask app with couple API endpoints: /api1 and /api2

Flask (flask_app.py):

app = Flask(__name__)
...
@app.route('/api1', methods=['POST'])
def api1():
...
@app.route('/api2', methods=['POST'])
def api2():
...
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Dockerfile:

...
# Copy application code
COPY flaskapp /app
WORKDIR /app

# Set entrypoint
ENTRYPOINT ["gunicorn", "-b", "0.0.0.0:5000", "flask_app:app"]

docker-compose:

services:

  nginx:
    image: nginx:latest
    container_name: nginx_container
    restart: always
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    depends_on:
      - app

  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: flask_container
    restart: always
    ports:
      - "5000:5000"
    volumes:
      - ./flaskapp:/app

nginx.conf:

events { 
    worker_connections 1024; 
}
http {
    client_max_body_size 0;
    server {
        listen 80;
            location / {
                proxy_pass http://flask_container:5000/;
            }
        client_max_body_size 0;
    }
}

I run it with Gunicorn and Nginx using docker-compose up. Everything starts properly.
Then I test it using Postman sending POST requests on this urls:

http://localhost:5000/api1
http://localhost:80/api1

but Postman returns 500 error every time.

Request to http://localhost:80/api1 also writes this message to Nginx console:

172.18.0.1 - - [08/Jun/2023:18:26:41 +0000] "POST /api1 HTTP/1.1" 500 265 "-" "PostmanRuntime/7.32.2"

I expected that POST requests will go to Flask API. Why it doesn’t?

2

Answers


  1. Chosen as BEST ANSWER

    500 error code meant error was happening on API side during code execution.

    For debugging could be used app.run(debug=True) or logging library in python.


  2. The Dockerfile needs to expose your port.

    # Copy application code
    COPY flaskapp /app
    WORKDIR /app
    
    # Install dependencies
    RUN pip install -r requirements.txt
    
    # Listen on port 5000
    EXPOSE 5000
    
    # Set entrypoint
    ENTRYPOINT ["gunicorn", "-b", "0.0.0.0:5000", "flask_app:app"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search