Bishwajit Vikram
Bishwajit Vikram

Reputation: 113

Web application using Python3 not working when Dockerized

HelloWorld-1.py

app = Flask(__name__)
@app.route('/')
def printHelloWorld():
    print("+++++++++++++++++++++")
    print("+ HELLO WORLD-1 +")
    print("+++++++++++++++++++++")
    return '<h1>Bishwajit</h1>'
    # return '<h1>Hello %s!<h1>' %name

if name == '__main__':
    app.run(debug='true')

Dockerfile

FROM python:3
ADD HelloWorld-1.py /HelloWorld-1.py
RUN pip install flask
EXPOSE 80
CMD [ "python", "/HelloWorld-1.py"]

Building docker using the below command

docker build -t helloworld .

Running docker image using below command

docker run -d --name helloworld -p 80:80 helloworld

when i run the below command

docker ps -a

i get the below output

CONTAINER ID  IMAGE      COMMAND               CREATED             STATUS             PORTS               NAMES

cebfe8a22493 helloworld "python /home/HelloW…" 2 minutes ago Up 2 minutes (unhealthy) 0.0.0.0:80->80/tcp helloworld

If I hit in the browser(127.0.0.1:5000), it does not give response, But when i run the python file individually, it runs properly in the browser.

Upvotes: 0

Views: 155

Answers (1)

programandoconro
programandoconro

Reputation: 2729

I reproduced your problem and there were four main problems:

  1. Not importing flask.
  2. Using name instead of __name__
  3. Not assigning the correct port.
  4. Not assigning the host.

This is how your HelloWorld-1.py should look like:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def printHelloWorld():
    print("+++++++++++++++++++++")
    print("+ HELLO WORLD-1 +")
    print("+++++++++++++++++++++")
    return '<h1>Bishwajit</h1>'
    # return '<h1>Hello %s!<h1>' %name

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

This is how you Dockerfile should look like:

FROM python:3
ADD HelloWorld-1.py .
RUN pip install flask
CMD [ "python", "/HelloWorld-1.py"]

Then simply build and run:

docker build . -t helloflask
docker run -dit -p 5000:5000 helloflask

Now go to localhost:5000 and it should work.

Additionally: You could actually assign any other port, for example 4444, and then go to localhost:4444:

docker run -dit -p 4444:5000 helloflask

Upvotes: 1

Related Questions