Tuesday, October 18, 2022

[FIXED] Why port binding don't working using with Docker SDK

Issue

I have one problem with Postgres image and Docker SDK (Python). If I use default Postgres port 5432 - all good. If I change port to 8133 - error:

"Connection to localhost:8133 refused. Check that the host and port are correct and that the postmaster is accepting TCP/IP connections."

OS: Windows 11

Python: 3.8

docker python package: vers. 6.0.0

Dockerfile:

FROM postgres:13.8

COPY . /docker-entrypoint-initdb.d/

Python code:

import dockerfile

client = docker.from_env()
...

client.images.build(path=docker_root, tag='my-image')
client.containers.run(
        image='my-image', 
        environment=[
            'POSTGRES_USER=mytest',
            'POSTGRES_PASSWORD=qwerty',
            'POSTGRES_DB=testdb'
        ], 
        ports={'8133/tcp': 5432},
        volumes=['C:/Users/.../AppData/Local/Temp/test-postgres':/var/lib/postgresql/data'], 
        name='my-container'
    )

If ports={'5432/tcp': 5432} - ok

If ports={'8133/tcp': 5432} - no connection

Where did I make mistake?


Solution

You have the ports: syntax backwards. Looking at the client.containers.run() documentation:

The keys of the dictionary are the ports to bind inside the container.... The values of the dictionary are the corresponding ports to open on the host....

The container port for PostgreSQL is always 5432, and this needs to be the dictionary key, before the colon.

client.containers.run(
        image='my-image', 
        ports={'5432/tcp': 8133}, # with 5432 on the left
        ...
)


Answered By - David Maze
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.