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

Better Stack Team
Updated on November 9, 2023

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:

     
    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:

     
    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:

     
    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:

     
    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.
  1. Start the New Container: Once you've created the new container with the modified port mapping, start it:

     
    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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github