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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With