docker tutorials

Docker EXPOSE Port only to the Host on Google Cloud

In this tutorial let’s see how to make docker expose port only to the host. In this tutorial we will run a demo application that listens for connections on a port that is exposed. Then let’s see how to expose this port only to the host on Google Cloud.

Docker EXPOSE Port

Below is the sample Dockerfile which expose port 8888 using expose instruction.

EXPOSE <port> [<port>/<protocol>...]

Dockerfile

FROM golang:1.14-alpine AS build

WORKDIR /src/
COPY main.go go.* /src/
RUN CGO_ENABLED=0 go build -o /bin/demo

FROM scratch
COPY --from=build /bin/demo /bin/demo
ENTRYPOINT ["/bin/demo"]
EXPOSE 8888/tcp

Port 8888 is the port that the container should listens on on the specified network ports during runtime. You can also specify whether the port listens on TCP or UDP. I had mentioned that the port listens on TCP. By default TCP is the protocol considered if not specified.

Note, the EXPOSE instruction actually will not publish the port. To publish the port you need to use -p flag on docker run command while running the container. Therefore, the exposed ports are published and mapped to the higher order ports.

Docker EXPOSE Port only to the Host

Note, in the above section the example Dockerfile makes application listen for connections on the port 8888, but this is container’s own private port and not forwarded to a port on your local machine.

You need to forward a port on your local machine to the private port on the container. Therefore, you will be able to connect to container’s port.

In order to tell Docker to forward a port or expose port only to the host port, you need to use -p flag in the following docker run command.

docker container run -p HOST_PORT:CONTAINER_PORT <DOCKER_MAGE_NAME>

For example,

$ docker container run -p 9999:8888 myhello

Any requests that is coming to the HOST_PORT 9999 on the local machine will be forwarded automatically only to the CONTAINER_PORT 8888 on the container.

That’s it. Hope it helped 🙂

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments