Add an environment via the Portainer API
Portainer's API lets you perform the same actions as via the Portainer UI, including adding new environments. This article explains how to add the following types of environments via the API:
A local environment using Docker socket communication.
A remote environment using TCP communication.
A remote environment using TCP communication secured via TLS.
The examples in this article use httpie to make HTTP calls from the command line to the Portainer API. Feel free to replace httpie with your preferred method.
Preparation
After deploying Portainer, you'll need to initialize your admin user. First, initialize the admin password:
Now, use the admin account to authenticate against the API. Generate an authorization token for your username. This token will provide you with the same permissions as the user who generated it.
The response is a JSON object containing the JWT token inside the jwt
field. Make a note of this token. You'll use it in the authorization header when making API calls.
The authorization header value must take the form Bearer JWT_TOKEN
. Using the above token as an example, the value would look like this:
The JWT token is valid for 8 hours after it is generated. Once it expires, you will need to generate a new token.
Adding an environment
Adding a local environment via the Docker socket
This query will create an environment called test-local
and will use the Docker socket to communicate with your environment.
This example requires you to bind-mount the Docker socket when running Portainer.
Run the following command:
The response is a JSON object representing the environment:
Make a note of the Id
value. It will be used to execute queries against the Docker Engine for the endpoint.
Adding a remote environment
This query will create an environment called test-remote
. It will communicate with your environment over TCP using the IP address 10.0.7.10
and port 2375
. Make sure you replace the example values with your own IP address and port.
The Docker API must be exposed on the provided IP address and port. To learn how to do this, refer to the Docker documentation.
Run the following command:
The response is a JSON object representing the environment:
Take a note of the Id
value. It will be used to execute queries against the Docker Engine for the environment.
Adding a remote environment with TLS
This query will create an environment called test-remote-tls
. It will communicate with your environment over TCP (secured with TLS) using the IP address 10.0.7.10
and port 2376
. Make sure you replace the example values with your own IP address and port.
The Docker API must be exposed on the provided IP address and port. To learn how to do this, refer to the Docker documentation.
Run the following command:
The response is a JSON object representing the environment:
Make a note of the Id
value. It will be used to execute queries against the Docker Engine for the environment.