# Update existing docker container's port mapping without creating new container

You forgot to expose a port in container? Don't worry, I have a solution to your problem. 

Just follow these steps.

**Step 1 : Stop the container you want to modify.**

```
sudo docker stop [containerId]
``` 

**Step 2: Stop your docker service**

To stop the docker.service, first we have to stop docker.socket. Otherwise, it will retrigger to start the docker.service again. So first stop the docker.socket with :


```
sudo systemctl stop docker.socket
``` 

and then docker.service with


```
sudo systemctl stop docker.service
``` 

You can verify whether the service has been stopped or not by using following command.


```
sudo systemctl status docker
``` 

It should output something like this


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650894569445/9mfIZq4Q1.png)

Now we are good to proceed.

**Step 3 : Update the container's `config.v2.json`**

This file will be located under  
```
/var/lib/docker/containers/[containerId]/config.v2.json

// or if docker is installed as snap
/var/snap/docker/common/var-lib-docker/containers/[containerId]
/config.v2.json
```

**For this example, lets say we want to expose the port 8000.**

- (a) Update entry for “ExposedPorts”

- (b) Update entry for “Ports”

So update the file as

```json
...
{
"Config": {
....
"ExposedPorts": {
"80/tcp": {},
"8000/tcp": {} //New port number to be exposed
},
....
},
"NetworkSettings": {
....
"Ports": {
 "80/tcp": [
 {
 "HostIp": "",
 "HostPort": "80"
 }
 ], 

//-------- Start ---------
 "8000/tcp": [ //New added port's mapping
 { 
 "HostIp": "",  // IP address of the container
 "HostPort": "8000" //Container's internal port that needs to be exposed. 
 } 
 ] 
//-------- End ---------
 },
....
}
```

`ctrl+x`

 `y`

 `Enter`

 To save and exit


**Step 4 : Update the container's `hostconfig.json`**

This file will be located under  
```
/var/lib/docker/containers/[containerId]/hostconfig.json

// or if docker is installed as snap

/var/snap/docker/common/var-lib-docker/containers/[containerId]
/hostconfig.json
```

- (a) Update entry for “PortBindings”

```json
....
 "PortBindings": {
 "80/tcp": [
 {
 "HostIp": "",
 "HostPort": "80"
 }
 ],
 "8000/tcp": [ //new added port 
 {
 "HostIp": "", // IP address of the host container.
 "HostPort": "8000" //Container's internal port that needs to be exposed. 
 }
 ]
 },
.....
```

`ctrl+x`

 `y`

 `Enter`

 To save and exit

Thats it, your port mapping has been updated.

Now start the container service again with
```
sudo systemctl start docker
```

Then start the modified container
```
sudo docker start [containerId]
```

**Note: **The port mapping in docker ps will not be modified unless the container is restarted.

Once the modified container has been started, check status with 
```
docker ps
```
and you will see the modified port changes.

**Hope this helps you. And Happy Coding !**

