Home > Software design >  Connecting to a Flask application deployed to EC2
Connecting to a Flask application deployed to EC2

Time:10-26

I've created a simple Flask application, containerized it using Docker, and pushed the container to my EC2 instance (using gzip and sftp). I've launched the image and confirm that it is running using docker ps:

Docker ps command output

The flask application expects to be reached on port 8080:

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

I've exposed this port in my Dockerfile:

FROM python:3.10-slim
ENV PYTHONUNBUFFERED True
...
EXPOSE 8080
CMD exec gunicorn --bind :8080 --workers 1 --threads 8 --timeout 0 main:app

After confirming the Dockerized Flask application was running on my EC2 instance I attempted to access it via my web browser using the instance Public IPv4 DNS address and port number:

ec2-digits.region.compute.amazonaws.com:8080

And received an error: ERR_CONNECTION_REFUSED

Immediately I added a new security rule on inbound traffic allowing any IPv4 traffic to ingress on port 8080: Security Configuration

Despite this, and after rebooting the instance, I still see the same error when attempting to contact my Flask app.

I've verified Flask is installed (v2.2.2) via pip3 list

docker container logs my_app does not show any error, before and after attempting connection on port 8080:

[2022-10-25 22:54:37  0000] [1] [INFO] Starting gunicorn 20.1.0
[2022-10-25 22:54:37  0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)
[2022-10-25 22:54:37  0000] [1] [INFO] Using worker: gthread
[2022-10-25 22:54:37  0000] [7] [INFO] Booting worker with pid: 7

What am I missing?

CodePudding user response:

Immediately I added a new security rule on inbound traffic allowing any IPv4 traffic to ingress on port 8080:

security groups never cause CONNECTION REFUSED. Security groups silently drop traffic so they cause timeouts, not connection refused.

By the way, you might not want to open your security group to all traffic unless your app is really ready to face the world. People can and will find the open port and attempt to abuse your app. so better to use your current IP for security group rules, even though you'll have to update when your IP changes.

Despite this, and after rebooting the instance, I still see the same error

rebooting your instance has nothing to do with security groups.

Did you expose 8080 when you ran the docker container? EXPOSE in the Dockerfile does not actually open any ports when the resulting image is run.

docker run .... -p 8080:8080 ....

  • Related