# How to assign a port mapping to an existing Docker container?

To assign a port mapping to an existing Docker container, you can follow these steps:

1. **Identify the Container**: Find the container ID or name of the Docker container you want to modify. You can use the `docker ps` command to list all running containers:
    
    ```bash
    docker ps
    ```
    
2. **Stop the Container (if it's running)**: If the container is running, stop it using the following command. Replace `CONTAINER_ID` with the actual ID or name of your container:
    
    ```bash
    docker stop CONTAINER_ID
    ```
    
3. **Remove the Existing Container (if necessary)**: If you prefer to keep the existing container's data, you can skip this step. However, if you want to start a new container based on the same image but with a different port mapping, you might need to remove the existing container. Be careful as removing a container deletes any changes made inside the container:
    
    ```bash
    docker rm CONTAINER_ID
    ```
    
4. **Create a New Container with the Desired Port Mapping**: You can create a new container based on the existing container's image and define the port mapping at this stage. Use the `p` flag to map the ports:
    
    ```bash
    docker run -p NEW_HOST_PORT:EXISTING_CONTAINER_PORT --name NEW_CONTAINER_NAME IMAGE_NAME
    ```
    
- `NEW_HOST_PORT`: This is the port on the host machine where you want to map the container's port.
- `EXISTING_CONTAINER_PORT`: This is the port inside the container that you want to expose.
- `NEW_CONTAINER_NAME`: This is the name you want to assign to the new container.
- `IMAGE_NAME`: This is the image of the existing container.

5. **Start the New Container**: Once you've created the new container with the modified port mapping, start it:
    
    ```bash
    docker start NEW_CONTAINER_NAME
    ```
    

Remember to replace the placeholder values (like `NEW_HOST_PORT`, `EXISTING_CONTAINER_PORT`, `NEW_CONTAINER_NAME`, and `IMAGE_NAME`) with your actual port numbers, container name, and image name.

By following these steps, you can re-create a container based on an existing image with a different port mapping. This allows you to assign a new port to an existing Docker container without directly modifying the port mappings of a running container.

[ad-logs]