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>...]
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>
$ 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 🙂
- How to Explore Docker Container’s File System ?
- Get Docker Container’s IP Address from the Host
- Copy Files between Host and Docker Container
- How to Start Stop Restart MariaDB on Linux OS ?
- How to set or change root password in Ubuntu Linux ?
- Putty Fatal Error No supported authentication methods available
- How to find which users belongs to a specific group in linux
- Give write permissions for specific user or group for specific folder in linux
- How to unzip a zip file from Terminal (Google Cloud Shell)
- Build a Docker Image with a Dockerfile and Cloud Build in GCP?
- How to remove an image tag from docker hub ?
- MariaDB – How to set max_connections permanently ?
- How to create GCP project on Google Cloud Platform
- Is it possible to change Google Cloud Platform Project ID ?
- Create non-root SSH user account and provide access to specific folders
- Delete docker repository from the docker hub