Jananath Banuka
Jananath Banuka

Reputation: 3963

Docker container exits after it starts

I am building and running this docker container. It is running a simple flask server. But when I run, it exited right after.

This is my Dockerfile

FROM python:3

WORKDIR /usr/src/app

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

COPY . .

EXPOSE 8080

# CMD ["python3", "-m",  "http.server", "8080"]
CMD ["python3", "./py_server.py"]

and this is py_server.py

from flask import Flask
app = Flask(__name__)

PORT = 8080

@app.route('/')
def hello_world():
    return "Hello World"

if __name__ == '__main__':
   app.run(PORT)

this is how I build and run the container respectively.

build:

docker build -t banuka/python-venv .

run:

docker run -dit -p 8080:8080 --name server1 banuka/python-venv:latest

Can someone tell me what I do wrong?

Upvotes: 0

Views: 4824

Answers (3)

Peter Prescott
Peter Prescott

Reputation: 908

There are several issues:

  1. You want the -it parameter, not -dit:
docker run -it -p 8080:8080 --name server1 banuka/python-venv:latest
  1. You are passing PORT as a variable to the app.run() function, so that it is interpreted as the first host parameter, rather than what you want, which is for it to be the port parameter. What you want is this: app.run(port=8080)

  2. As @Alexandre pointed out, if you're accessing the host remotely, then you need to explicitly bind it to host='0.0.0.0', so we need app.run(host='0.0.0.0',port=8080)

Upvotes: 2

Alexandre Juma
Alexandre Juma

Reputation: 3323

You have a bug in your Flask Code. You're trying to configure Flask Server PORT in a wrong way. This will throw the error you're experiencing:

AttributeError: 'int' object has no attribute 'startswith'

You should configure your Flask Server Port with the following way

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return "Hello World"

if __name__ == '__main__':
   app.run(host='0.0.0.0',port=8080)

The documentation: https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.run

EDIT: Added host='0.0.0.0' so you can access your Flask Server remotely.

Upvotes: 1

OrDushi
OrDushi

Reputation: 96

you are maybe running procces that finishes and then exit ? if you run you py script and it finishes so your container will be closed to ... try using while(true) //and then your code

Upvotes: 0

Related Questions