How to Use Docker API: Syntax, Example, and Tips
You can use the
Docker API to control Docker programmatically by sending HTTP requests to the Docker daemon's REST endpoint. Use tools like curl or client libraries in languages like Python or Go to interact with the API for tasks like managing containers and images.Syntax
The Docker API uses HTTP methods (GET, POST, DELETE, etc.) to interact with Docker daemon endpoints. Each endpoint corresponds to a Docker resource like containers or images.
Example parts:
- HTTP method: The action to perform (e.g., GET to list, POST to create).
- URL endpoint: The resource path (e.g.,
/containers/jsonto list containers). - Headers: Usually
Content-Type: application/jsonfor JSON data. - Body: JSON data for POST or PUT requests to specify details.
bash
curl --unix-socket /var/run/docker.sock http://localhost/containers/json
Example
This example shows how to list running Docker containers using the Docker API with curl. It sends a GET request to the Docker daemon socket and returns container details in JSON.
bash
curl --unix-socket /var/run/docker.sock http://localhost/containers/json
Output
[{"Id":"e90e34656806","Names":["/my_container"],"Image":"nginx","State":"running","Status":"Up 2 hours"}]
Common Pitfalls
Common mistakes when using the Docker API include:
- Not using the correct socket or TCP endpoint to connect to the Docker daemon.
- Missing or incorrect HTTP headers, especially
Content-Type: application/jsonfor POST requests. - Trying to access the API without proper permissions (usually requires root or Docker group membership).
- Not handling JSON responses properly.
Example of a wrong request missing the socket:
bash
curl http://localhost/containers/json # Correct way: curl --unix-socket /var/run/docker.sock http://localhost/containers/json
Quick Reference
Key Docker API endpoints:
GET /containers/json- List containersPOST /containers/create- Create a containerPOST /containers/{id}/start- Start a containerDELETE /containers/{id}- Remove a containerGET /images/json- List images
Use curl --unix-socket /var/run/docker.sock to connect locally.
Key Takeaways
Use HTTP requests to interact with Docker daemon via its REST API.
Connect locally using the Unix socket at /var/run/docker.sock with curl or client libraries.
Always include proper headers and JSON body when required.
Ensure you have permission to access the Docker daemon socket.
Common endpoints include /containers/json for listing and /containers/create for creating containers.