DEV Community

Hemanth B
Hemanth B

Posted on


How to add port on unpublished running docker container

While executing a docker command, forgot give -p as parameter, then container become inaccessible to others with locathost ip-address.

To access the docker which is running is without publishing port using the tool socat.

For example, you have nginx docker and executed below command to running nginx without publishing the port.

docker run --name nginx -d nginx
Enter fullscreen mode Exit fullscreen mode

When you execute below command, you will not be able to access.

$ curl localhost:80
curl: (7) Failed connect to localhost:80; Connection refused
$ curl localhost:8080
curl: (7) Failed connect to localhost:8080; Connection refused
Enter fullscreen mode Exit fullscreen mode

To make the port accessible, you don't need stop and remove
the container, instead without stopping the container, using socat docker port can be made accessible make sure running socat docker in same network where nginx is running.

Execute below docker command to get ip address of the nginx container.

$ docker inspect nginx -f "{{json .NetworkSettings.Networks }}" | jq
  "bridge": {
    "IPAMConfig": null,
    "Links": null,
    "Aliases": null,
    "NetworkID": "b813449892718ab3fb3559d1009df9ac8ce53a445ab1de3158396362371e99f6",
    "EndpointID": "bbc0b7510a66c9a84e49d6987daf8cdc7634af2f8615d4cb4c68f579fabb6a44",
    "Gateway": "",
    "IPAddress": "",
    "IPPrefixLen": 16,
    "IPv6Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "MacAddress": "02:42:ac:11:00:02",
    "DriverOpts": null
Enter fullscreen mode Exit fullscreen mode

Copy the Ip Address of the nginx paste next to TCP-CONNECT in below docker command.

docker run -d --name socat -p 8080:1234 alpine/socat TCP-LISTEN:1234,fork TCP-CONNECT:
Enter fullscreen mode Exit fullscreen mode

Now nginx container output will be re-direct from socat through 1234 -> 8080.

If you execute curl command, now nginx container will become accessible.

$ curl localhost:8080
<!DOCTYPE html>
<title>Welcome to nginx!</title>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href=""></a>.<br/>
Commercial support is available at
<a href=""></a>.</p>

<p><em>Thank you for using nginx.</em></p>
Enter fullscreen mode Exit fullscreen mode

For demo, created a video through asciinema, please check below.


Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git