Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the name of a Docker container using REST API

Tags:

docker

I am attempting to create and start a container via the REST API. That is, using the following API:

curl --http1.0 --request POST --header "Content-Type: application.json" http://$DOCKER_HOST:4243/containers/create --data @create.json

where create.json is a JSON file of desired properties. I would like to assign a specific name to the container. One can do this via the docker CLI using the --name parameter on the run command:

docker run --name "my_name" my_image

The documentation for creating a container (https://docs.docker.com/reference/api/docker_remote_api_v1.15/#create-a-container) provides an example JSON payload. A name attribute is not listed. I tried the following variations for a name attribute:

"Name": "my_name"
"Names": [ "my_name" ]
"Names": [ "/my_name" ]
"Name": "/my_name"

all to no avail. The variations are inspired by the results of a query:

curl --http1.0 http://$DOCKER_HOST:4243/containers/json

which returns entries that include:

"Names":["/elegant_mccarthy"]
like image 907
kalantar Avatar asked Dec 25 '22 03:12

kalantar


1 Answers

You include name as a query param, not in the JSON.

From the docs (on the page you linked):

Query Parameters:

name – Assign the specified name to the container. Must match /?[a-zA-Z0-9_-]+.

So probably something like:

curl --http1.0 --request POST --header "Content-Type: application.json" http://$DOCKER_HOST:4243/containers/create?name=your-name --data @create.json

When in doubt:

You can use socat to sit between your Docker CLI calls and the unix socket it uses to talk to the daemon to see exactly what's happening when you use the docker client, since it just talks to the API itself.

In one terminal:

socat -t100 -v UNIX-LISTEN:/tmp/proxysocket.sock,mode=644,reuseaddr,fork UNIX-CONNECT:/var/run/docker.sock

And in another terminal:

export DOCKER_HOST="unix:///tmp/proxysocket.sock"
docker run -ti --name=test ubuntu:14.04 /bin/bash 

And you'll be able to see in the output of the first terminal:

2014/10/26 02:20:15.176744 length=564 from=0 to=563

POST /v1.15/containers/create?name=test HTTP/1.1\r

Host: /tmp/proxysocket.sock\r

User-Agent: Docker-Client/1.2.0-dev\r

Content-Length: 370\r

Content-Type: application/json\r

Accept-Encoding: gzip\r

like image 132
Chris McKinnel Avatar answered Feb 24 '23 02:02

Chris McKinnel