GianAnge
GianAnge

Reputation: 633

Why to access to a container by browser I have to set same host:container ports?

as the question says. Here it is my situation.
My project folder is:

PROJ    
|____docker-compose.yml  
|____servDir/  
        |____Dockerfile  
        |____server.py  

In the docker-compose.yml:


service1:
    image: img1:v0.1
    container_name: cont1
    build: ./servDir/.
    ports:
      - "5001:5002"

server.py:

from flask import Flask, request
import json

app = Flask(__name__)
PORT = 5001

@app.route("/greetings/")
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=int(PORT), debug=True)

When I run docker-compose up and go to http://localhost:5001/greetings/ I receive a ERR_CONNECTION_REFUSED.

Instead, if I set ports as 5001:5001, I'm able to receive the page content.

Why? Should I set them always equals, in order to reach the container by browser?

I thought that ports configuration was HOST:CONTAINER, and that browser would be a HOST sevice.

UPDATE:
Dockerfile:

FROM python:3

WORKDIR    /home/python/app/
COPY       . /home/python/app/
RUN        chmod a+x *.py

CMD        ["python", "./server.py"]

Upvotes: 0

Views: 62

Answers (1)

AppyGG
AppyGG

Reputation: 382

This is right : HOST:CONTAINER

Try to use this to expose it for your localhost and LAN :

service1:
    image: img1:v0.1
    container_name: cont1
    build: ./servDir/.
    ports:
      - "0.0.0.0:5001:5002"

or this to only your localhost :

service1:
    image: img1:v0.1
    container_name: cont1
    build: ./servDir/.
    ports:
      - "127.0.0.1:5001:5002"

Also, you wrote :

When I run docker-compose up and go to http://localhost:6002/greetings/ I receive a ERR_CONNECTION_REFUSED.

Looking at your docker compose you should access it like that instead:

http://localhost:6002 --> http://localhost:5001

Change server.py config :

from flask import Flask, request
import json

app = Flask(__name__)
PORT = 5002

@app.route("/greetings/")
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=int(PORT), debug=True)

Upvotes: 1

Related Questions