This is a simple Python Flask application that prints the hostname and IP address of the container it's running in.
- AWS EC2 instance (Amazon Linux 2 or similar)
sudo yum install git -ygit clone https://github.com/arumullayaswanth/python-flask-docker.git
cd python-flask-dockersudo yum install python3 -y
sudo yum install python3-pip -ypip3 install -r requirements.txtcd src/
lspython3 app.pyπ To check running processes:
ps aux | grep pythonnohup allows your app to continue running even after terminal disconnect:
nohup python3 app.py > flask.log 2>&1 &πͺ Check logs:
tail -f flask.logβ If port 5000 is in use:
lsof -i :5000
kill -9 <PID>This guide walks you through setting up a Python Flask app inside a Docker container on an AWS EC2 instance.
- AWS EC2 instance (Amazon Linux 2 or similar)
- Security group allowing inbound traffic on port 5000
- SSH access to EC2 instance
sudo yum update -y
sudo yum install git -y
sudo yum install python3-pip -ygit clone https://github.com/arumullayaswanth/python-flask-docker.git
cd python-flask-dockerpip3 install -r requirements.txtsudo yum install docker -y
sudo systemctl start docker
sudo systemctl enable docker
sudo systemctl status dockerIf
Ensure the file has the following content:
FROM python:3.13-alpine
LABEL maintainer="yaswanth@gmail.com"
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 5000
ENTRYPOINT ["python"]
CMD ["src/app.py"]docker build -t flask-docker-app .
docker imagesdocker run -d -p 5000:5000 flask-docker-app
docker psOpen your browser and visit:
http://<your-ec2-public-ip>:5000
# List running containers
docker ps
# List all containers
docker ps -a
# Stop a container
docker stop <container-id>
# Kill a container
docker kill <container-id>
# Remove stopped containers
docker container pruneYou canβt run Flask directly on Lambda, but hereβs what you can do:
- Use AWS Lambda + API Gateway instead of Flask.
- Convert Flask logic into a Lambda-compatible handler:
import json
import socket
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': json.dumps({
'hostname': socket.gethostname(),
'ip': socket.gethostbyname(socket.gethostname())
})
}- Create a zip package of your code.
- Deploy it to Lambda.
- Use API Gateway to trigger it.
ps aux | grep python
kill -9 <PID> # If needed
docker ps
docker stop <container_id>Your Flask app is now running in Docker on EC2, and optionally portable to Lambda.