Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mount volume using Docker API

Tags:

docker

I have a Docker host that is controlled using Docker API, like this.

I can create a new volume and a new container using this API very easily.

But how can I create new container and mount this volume to this container, using only API?

like image 928
Roman Zavodskikh Avatar asked Sep 27 '17 17:09

Roman Zavodskikh


People also ask

Can you mount a Docker volume on the host?

You can mount host volumes by using the -v flag and specifying the name of the host directory. Everything within the host directory is then available in the container. What's more, all the data generated inside the container and placed in the data volume is safely stored on the host directory.

Can you mount a volume while building your Docker image?

When building an image, you can't mount a volume. However, you can copy data from another image! By combining this, with a multi-stage build, you can pre-compute an expensive operation once, and re-use the resulting state as a starting point for future iterations.


1 Answers

You can mount the previously created volume (let's say volume1) to the container using the HostConfig in the create request. In the HostConfig you can specify the mounts (Mounts) you want to create.

A Mount would be like:

{
   "Target":   "path/in/the/container",
   "Source":   "volumeName",
   "Type":     "volume", 
   "ReadOnly": false
}

So the informations you should add to the create request is the next:

"HostConfig": {
    "Mounts": [
        {
           "Target":   "path/in/the/container",
           "Source":   "volume1",
           "Type":     "volume", 
           "ReadOnly": false
        }
     ]
}

I also recommend you to dig into this documentation from Docker. You can find a lot of good and useful information there.

https://docs.docker.com/engine/api/v1.27/#operation/ContainerCreate

like image 151
Fontinalis Avatar answered Sep 17 '22 20:09

Fontinalis