To bind a docker container port with host, use this command –
docker run -p{host_port}:{container_port} {image_name}
Let’s see this using an example.
First, we need a docker image which exposes a port. Generally the database images do expose some standard ports. Here we will install mongodb –
docker pull mongo
Now we need to start the container. But before that we should know, what port is exposed by Mongodb. We can get this information from their website and also from docker hub page. According to it –
The MongoDB server in the image listens on the standard MongoDB port,
https://hub.docker.com/_/mongo27017
, so connecting via Docker networks will be the same as connecting to a remotemongodb
.
The next decision we need to take is, what port on the host are we going to bind to it. If you are not using 27017 already or running multiple containers of mongodb, then you can simply use the same port. Otherwise use any which is available. Let’s use 27020 –
docker run -p27020:27017 mongo
This will bind the port and run a container –
Since we didn’t use -d
flag (for detached mode), it gets attached to this terminal window and showing the logs. If we run in detached mode –
docker run -d -p27020:27017 mongo
Now our terminal will be free to continue the work –
We can check the status of this container –
docker ps
You can see from this image that our container is running and it’s port 27017 is bounded to the host port 27020. All the requests coming to the host port 27020 will be addressed by this container.
Kubernetes Series
- Introduction to Kubernetes
- Introduction to Docker, Containers, Images & Repository
- Install and Run Docker Images
- Docker Image – FROM, RUN, COPY, ENTRYPOINT, CMD, EXPOSE explained
- Why docker run or start command not running my container?
- How to list all docker images in system?
- How to list all docker containers?
- How to start/stop a docker container?
- Difference between docker run and docker start
- How to bind docker container port with host?
- How to get logs of docker container?
- How to live stream logs of docker container?
- Set custom name to a docker container
- Access docker container filesystem & terminal
- Getting docker details using docker inspect
- Kyverno – Installation, Policies, Testing, Reporting, Monitoring, Security
- Complete Kubernetes Project Step By Step
- Introduction to Kubernetes Objects