How can I add a volume to an existing Docker container?

Better Stack Team
Updated on October 5, 2023

You cannot directly add a volume to an existing Docker container, but you can create a new container with the same configuration as the existing container, but with an additional volume mounted. Here are the steps:

  1. Create a new volume that you want to attach to the container:

     
    docker volume create my-new-volume
    
  2. Create a new container with the same configuration as the existing container, but with the additional volume mounted:

     
    docker run -d --name my-new-container \
    --volumes-from my-existing-container \
    -v my-new-volume:/path/to/new/volume \
    my-image
    

    This will create a new container called my-new-container that is based on the same image as my-existing-container. The --volumes-from option tells Docker to mount all the volumes from the existing container to the new container. The -v option mounts the new volume to the new container. You can replace /path/to/new/volume with the path where you want to mount the volume in the new container.

  3. Stop and remove the old container:

     
    docker stop my-existing-container
    docker rm my-existing-container
    

    This will stop and remove the old container. You can also choose to keep the old container running while you test the new container to make sure everything is working correctly.

  4. Rename the new container to the name of the old container:

     
    docker rename my-new-container my-existing-container
    

    This will rename the new container to the same name as the old container, so any scripts or commands that reference the old container by name will still work.

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