API Reference

JuliaDockerClient.commit_containerMethod

commitcontainer(containername::String, repotag::String; authtoken::String="")

Commits the current state of a container to a new image with a specified repository tag. This is similar to taking a snapshot of the container's current state and saving it as an image.

Arguments

  • container_name::String: The name of the Docker container to commit as an image.
  • repo_tag::String: The repository tag to apply to the new image. This should include the repository name and tag (e.g., "myrepo/myimage:latest").
  • auth_token::String="" (optional): Authentication token for Docker API access.

Behavior

  • Searches for the specified container by name.
  • If the container exists, commits its current state to a new image with the specified repository tag.
  • Prints a message indicating the action taken or if the container does not exist.

Example

commitcontainer("mycontainer", "myrepo/myimage:latest")

Commits the state of "my_container" to a new image tagged as "myrepo/myimage:latest".

source
JuliaDockerClient.create_containerMethod

createcontainer(containerconfig::Dict, containername::String; authtoken::String="")

Creates and(or) starts a (existing) Docker container based on the provided configuration. If a container with the specified name already exists and is stopped, it will be started. If it doesn't exist, a new container will be created and the started.

Arguments

  • container_config::Dict: Configuration for the Docker container, including image, environment variables, and ports.
  • container_name::String: The desired name for the container. Must be unique.
  • auth_token::String="" (optional): Authentication token for Docker API access.

Behavior

  • Checks for an existing container with the given name.
  • If the container exists and is stopped, it is started.
  • If the container does not exist, a new one is created with the specified configuration.
  • Prints a message indicating the action taken.

Example

containerconfig = Dict("Image" => "nginx:latest", "Env" => ["EXAMPLEVAR=examplevalue"]) containername = "mynginxcontainer" createcontainer(containerconfig, container_name)

This attempts to create or start a container named my_nginx_container using the nginx:latest image.

source
JuliaDockerClient.docker_api_getFunction
docker_api_get(endpoint::String, params::Dict=Dict(); auth_token::String="") -> Any

Send a GET request to the Docker API via a Unix socket, particularly for querying Docker resources.

Arguments

  • endpoint::String: The Docker API endpoint to which the GET request is sent.
  • params::Dict=Dict(): A dictionary of query parameters to append to the endpoint. Defaults to an empty dictionary.
  • auth_token::String="": An optional authentication token used for accessing secured Docker resources.

Returns

Any: The response body parsed from JSON format. The actual return type depends on the specific endpoint and the structure of the response.

Example

images = dockerapiget("images/json", Dict("all" => "true"), authtoken="yourauth_token")

This function constructs the full URL for the request, including query parameters, and calls unix_socket_get to send the request through a Unix socket. It then extracts the body of the response and parses it from JSON.

Notes

  • Ensure that unix_socket_get and get_response_body are properly implemented and accessible.
  • The function assumes that the response body is in JSON format and parses it accordingly. Non-JSON responses will lead to parsing errors.
  • The HTTP.escapeuri function is used to correctly encode the query parameters.
  • Authentication is managed via the auth_token, which is incorporated into the request header if provided.
source
JuliaDockerClient.docker_api_postFunction
docker_api_post(endpoint::String, params::Dict=Dict(); auth_token::String="") -> Any

Send a POST request to the Docker API via a Unix socket, commonly used for actions like creating or modifying Docker resources.

Arguments

  • endpoint::String: The Docker API endpoint to which the POST request is sent.
  • params::Dict=Dict(): A dictionary of data to be sent as the body of the POST request. Defaults to an empty dictionary.
  • auth_token::String="": An optional authentication token for secured Docker operations.

Returns

Any: The parsed response body from JSON format. The actual return type depends on the specific endpoint and the response structure.

Example

response = dockerapipost("containers/create", Dict("Image" => "alpine", "Cmd" => ["echo", "hello world"]), authtoken="yourauth_token")

This function serializes the provided parameters into a JSON string for the POST request body. It then calls unix_socket_post to send the request and handles the response, extracting and parsing the response body from JSON.

Notes

  • unix_socket_post is used to send the request and must be implemented to handle POST requests correctly.
  • The function assumes the response body is in JSON format. Non-JSON responses will cause parsing errors.
  • It checks for a "200 OK" status within unix_socket_post and will raise an error for non-200 responses.
  • Authentication is managed via the auth_token, which is included in the request if provided.
source
JuliaDockerClient.get_response_bodyMethod
get_response_body(response::String) -> String

Parse the body from a chunked HTTP response string.

This function handles chunked transfer encoding of HTTP responses. It splits the response into chunks based on the chunk size specified in the response and reconstructs the full body.

Arguments

  • response::String: The raw HTTP response string, including headers and the chunked body.

Returns

  • String: The parsed response body.

Example

response = "HTTP/1.1 200 OK

Content-Type: text/plain Transfer-Encoding: chunked

5 Hello 0

"

body = getresponsebody(response) println(body) # Output: Hello

In this example, response is a simulated raw HTTP response with a chunked body. The get_response_body function parses the response and extracts the body content.

source
JuliaDockerClient.list_containersMethod
list_containers(; all::Bool=true, auth_token::String="") -> Any

List all Docker containers on the host.

Arguments

  • all::Bool=true: Flag to list all containers. If false, only running containers are listed.
  • auth_token::String="": Optional authentication token.

Returns

Any: A JSON array of container details as returned by the Docker API.

Example

containers = listcontainers(all=true, authtoken="yourauthtoken")

Notes

  • This function queries the 'containers/json' endpoint of the Docker API.
  • The docker_api_get function is used to make the GET request with the specified parameters.
source
JuliaDockerClient.list_imagesMethod
list_images(; auth_token::String="") -> Any

List all Docker images available in the local Docker image store.

Arguments

  • auth_token::String="": An optional authentication token for accessing secured Docker resources.

Returns

Any: A JSON array of images and their details as returned by the Docker API.

Example

images = listimages(authtoken="yourauthtoken")

Notes

  • This function calls the Docker API's 'images/json' endpoint to retrieve a list of all images.
  • The response is expected to be in JSON format and contains details about each image.
  • The docker_api_get function is used to make the GET request. It should be properly implemented to handle GET requests and include authentication if provided.
source
JuliaDockerClient.parse_and_print_status_messagesMethod
parse_and_print_status_messages(json_response::String)

Parse and print status messages from a JSON-encoded response string.

This function is designed to process a JSON string, typically returned from Docker API calls, and print out status messages. It is particularly useful for handling streaming responses from the Docker API, such as the output from image pull or build operations.

Arguments

  • json_response::String: A string containing a JSON-encoded response from the Docker API.

Usage

parseandprintstatusmessages(response_json)

Notes

  • The function expects json_response to be a valid JSON string.
  • It assumes that the JSON response is either an array of objects, each with a "status" field, or a single JSON object.
  • If the response is an array, it iterates through each element, printing the value of the "status" field.
  • If the response does not conform to the expected format (e.g., it is not an array), the function prints an "Unexpected response format" message.
  • This function is useful for scenarios where real-time feedback from a Docker operation is required.
source
JuliaDockerClient.prepare_container_resources_configMethod
prepare_container_resources_config(cores::Int, memory_gb::Int) -> Dict

Generate a container configuration dictionary with specified CPU and memory resource limits.

This function prepares a configuration dictionary for a Docker container with specific CPU core and memory settings. The memory limit is specified in gigabytes (GB) and internally converted to bytes, as Docker requires memory limits to be specified in bytes.

Arguments

  • cores::Int: The number of CPU cores to allocate to the container.
  • memory_gb::Int: The memory limit for the container in gigabytes.

Returns

  • Dict: A container configuration dictionary with HostConfig settings for CPU and memory resources.

Example

cores = 4 memorygb = 2 containerconfig = preparecontainerresourcesconfig(cores, memorygb)

This example creates a container configuration for a Docker container with 4 CPU cores and 2 GB of memory.

source
JuliaDockerClient.pull_imageMethod

pullimage(imagename::String; auth_token::String="")

Pulls a Docker image from a registry. This function initiates a download of the specified image from its configured registry into the local Docker environment.

Arguments

  • image_name::String: The name of the Docker image to pull. This should include the tag if a specific version is desired (e.g., ubuntu:latest).
  • auth_token::String="" (optional): An authentication token for accessing secured registries. The token is used to authenticate the pull request with the registry.

Behavior

  • Initiates a pull operation for the specified image. The function waits for the operation to complete, pulling the image into the local Docker environment.

Example

imagename = "nginx:latest" pullimage(imagename; authtoken="yourauthtoken_here")

This example pulls the nginx:latest image from its registry, using the provided auth_token for authentication if necessary.

source
JuliaDockerClient.push_imageMethod

pushimage(imagename::String; auth_token::String="")

Pushes a Docker image to a registry. This function requires the image to be already present in the local Docker environment and properly tagged to match the target registry's requirements.

Arguments

  • image_name::String: The name (and tag) of the Docker image to push to the registry. The name should include the registry path if pushing to a specific registry other than Docker Hub.
  • auth_token::String="" (optional): An authentication token for accessing secured registries. The token is used to authenticate the push request with the registry.

Behavior

  • This function initiates a push operation for the specified image to its configured registry. The operation's success depends on network conditions, access permissions, and the existence of the image.

Example

imagename = "myregistry.com/myimage:latest" pushimage(imagename; authtoken="myauthtoken")

This example pushes myimage:latest to myregistry.com, using my_auth_token for registry authentication.

source
JuliaDockerClient.registry_loginFunction
registry_login(registry_url::String="registry.git.nilu.no", username::String="FACT_token", password::String="glpat-1zG-TQx___xLsPjj2vsG") -> String

Create a base64-encoded authentication token for Docker registry operations.

This function generates an authentication token that can be used in the X-Registry-Auth header for Docker API requests that require authentication, such as pushing or pulling private images.

Arguments

  • registry_url::String="registry.git.nilu.no": The URL of the Docker registry. Defaults to "registry.git.nilu.no".
  • username::String="FACT_token": The username for the Docker registry.
  • password::String="glpat-1zG-TQx___xLsPjj2vsG": The password or token for the Docker registry.

Returns

String: A base64-encoded JSON string that contains the authentication details.

Example

encodedauth = registrylogin("registry.example.com", "myusername", "mypassword")

Notes

  • The function constructs a dictionary with the provided credentials and the registry URL, then converts this dictionary into a JSON string.
  • The JSON string is encoded in base64, which is the format expected by the Docker Engine API for authentication headers.
  • Be cautious with hardcoding credentials. In a production environment, consider secure ways to handle sensitive data like passwords or tokens.
source
JuliaDockerClient.remove_containerMethod

removecontainer(containername::String; force::Bool=false, auth_token::String="")

Removes a Docker container specified by its name. Can forcefully remove the container if it is running.

Arguments

  • container_name::String: The name of the container to remove.
  • force::Bool=false: Indicates whether to forcibly remove the container, including its volumes and any running instances.
  • auth_token::String="" (optional): Authentication token for Docker API access.

Behavior

  • Checks for an existing container with the given name, including stopped containers.
  • If the container exists, it attempts to remove it, forcibly if force is true.
  • Prints a message indicating whether the container was removed or if it did not exist.

Example

containername = "mynginxcontainer" removecontainer(container_name; force=true)

This removes the container named my_nginx_container, forcibly terminating it and removing its volumes if necessary.

source
JuliaDockerClient.remove_imageMethod

removeimage(imagename::String; force::Bool=false, auth_token::String="")

Removes a Docker image from the local environment. This function can forcefully remove the image if it is in use or has dependent child images.

Arguments

  • image_name::String: The name (and optionally the tag) or ID of the Docker image to be removed.
  • force::Bool=false: Whether to forcefully remove the image even if it is in use or has dependent child images.
  • auth_token::String="" (optional): An authentication token. While typically not required for local operations, it might be necessary for certain secured environments.

Behavior

  • Attempts to remove the specified image from the local Docker environment. If force is set to true, it will remove the image even if there are complications such as the image being in use.

Example

imagename = "nginx:latest" removeimage(imagename; force=true, authtoken="yourauthtoken_here")

This example forcefully removes the nginx:latest image from the local Docker environment, using the provided auth_token if necessary.

source
JuliaDockerClient.stop_containerMethod

stopcontainer(containername::String; auth_token::String="")

Attempts to stop a running Docker container specified by its name. If the container is not found or is not running, a message is printed to indicate this.

Arguments

  • container_name::String: The name of the Docker container to stop.
  • auth_token::String="" (optional): Authentication token for Docker API access.

Behavior

  • Searches for a running container with the specified name.
  • If found and running, sends a request to stop the container.
  • Prints a message indicating whether the container was stopped or if it was not running.

Example

stopcontainer("mycontainer")

Stops a running container named "my_container".

source
JuliaDockerClient.tag_imageMethod
tag_image(image_name::String, old_tag_name::String, new_image_name::String, new_tag_name::String; auth_token::String="")

Tags a Docker image with a new name and tag. This operation is local to the Docker environment and does not involve network communication with a registry.

Arguments

  • image_name::String: The name of the Docker image to be tagged. This does not include the tag of the source image.
  • old_tag_name::String: The existing tag of the Docker image to be tagged. This specifies the exact version of the image_name to be used.
  • new_image_name::String: The new name to apply to the image. This name can include a new registry path and repository but does not include the tag.
  • new_tag_name::String: The new tag to apply to the image. This specifies the version of the new_image_name.
  • auth_token::String="" (optional): While tagging typically does not require authentication, if this function is part of a broader workflow that includes registry interaction, an auth token can be specified.

Behavior

  • Applies the new_image_name and new_tag_name to the image identified by image_name and old_tag_name. If the operation is successful, the image will be available under both the old name/tag and the new name/tag.

Example

imagename = "myimage" oldtagname = "oldtag" newimagename = "myregistry.com/myimage" newtagname = "newtag" tagimage(imagename, oldtagname, newimagename, newtagname; authtoken="myauthtoken")

This example retags myimage:oldtag as myregistry.com/myimage:newtag, potentially preparing it for pushing to myregistry.com.

source
JuliaDockerClient.test_connectionMethod
test_connection() -> Bool

Test the connection to the Docker Unix socket.

This function attempts to establish a connection to the Docker Unix socket, indicated by the DOCKER_UNIX_SOCKET global constant. It is used to verify if the Docker daemon is accessible and the Unix socket is available.

Returns

Bool: true if the connection is successfully established, false otherwise.

Example

isconnected = testconnection()

Notes

  • The function tries to open a socket connection using the path specified in DOCKER_UNIX_SOCKET.
  • If the connection is successful, the socket is closed immediately, and the function returns true.
  • If any error occurs during the connection attempt (such as the socket not being available), the function catches the exception, prints an error message, and returns false.
  • This function is useful for preliminary checks to ensure that the Docker environment is set up correctly and the API is accessible.
source
JuliaDockerClient.unix_socket_getMethod
unix_socket_get(http_request::String, auth_token::String) -> String

Send a GET request through a Unix socket to the Docker API.

Arguments

  • http_request::String: The specific API endpoint and query string for the GET request.
  • auth_token::String: Authentication token for registry access. If the token is empty, no authentication header is added.

Returns

String: The raw HTTP response as a string.

Usage

response = unix_socket_get("images/json", "auth_token_here")

This function connects to the Docker Unix socket, constructs a GET HTTP request with the specified endpoint and optional authentication, sends the request, and returns the raw response as a string. The response includes both the HTTP headers and the body.

Notes

  • The DOCKERUNIXSOCKET and DOCKERAPIMAIN_ENTRYPOINT are assumed to be globally defined constants indicating the path to the Unix socket and the main entry point of the Docker API, respectively.
  • This function does not parse the response; it returns the raw HTTP response for further processing.
source
JuliaDockerClient.unix_socket_postMethod
unix_socket_post(http_request::String, post_data::String, content_type::String="application/json", auth_token::String) -> String

Send a POST request through a Unix socket to the Docker API.

Arguments

  • http_request::String: The specific API endpoint for the POST request.
  • post_data::String: The data to be sent in the body of the POST request.
  • content_type::String="application/json": The content type of the POST request. Defaults to "application/json".
  • auth_token::String: Authentication token for registry access. It is included in the request's headers.

Returns

String: The raw HTTP response as a string.

Example

response = unixsocketpost("containers/create", "{"Image": "alpine", "Cmd": ["echo", "hello world"]}", "application/json", "authtokenhere")

This function connects to the Docker Unix socket and constructs a POST HTTP request with the specified endpoint, data, and optional authentication. It sends the request and returns the raw response as a string. The response includes both the HTTP headers and the body.

Notes

  • The DOCKER_UNIX_SOCKET and DOCKER_API_MAIN_ENTRYPOINT are assumed to be globally defined constants indicating the path to the Unix socket and the main entry point of the Docker API, respectively.
  • The function checks for a "200 OK" status in the response. If not found, it raises an error with the response details.
  • This function does not parse the response; it returns the raw HTTP response for further processing.
source
JuliaDockerClient.JuliaDockerClientModule
Module JuliaDockerClient

A Julia module for interacting with the Docker Engine API, enabling the management of Docker containers and images directly from Julia code.

This module provides a set of functions that allow users to perform various operations such as pulling and pushing images, creating, stopping, and removing containers, and more, using the Docker API.

Dependencies

  • HTTP.jl: For handling HTTP requests and responses.
  • JSON.jl: For parsing and constructing JSON payloads.
  • Sockets: For Unix socket communication with Docker.
  • Base64: For encoding authentication tokens.

Constants

  • DOCKER_API_MAIN_ENTRYPOINT: The main entry point of the Docker API, defaulting to 'v1.40'.
  • DOCKER_API_HOST: The host where the Docker API is accessible, defaulting to 'localhost'.
  • DOCKER_API_URL: Constructs the full URL for the Docker API.
  • DOCKER_UNIX_SOCKET: The path to the Unix socket for Docker, defaulting to '/run/user/${UID}/podman/podman.sock'.

Usage

The module provides various functions exported from included submodules. Before using these functions, ensure that the Docker Engine is running and accessible at the specified Unix socket or API URL.

Exported Functions

  • Docker API Interaction:
    • test_connection: Tests the connection to the Docker Unix socket.
    • registry_login: Generates an authentication token for Docker registry operations.
    • prepare_container_resources_config: Prepares the resource configuration for a container with constyrained resources (CPUs and memory in GB).
  • Image Management:
    • pull_image: Pulls a Docker image from a registry.
    • list_images: Lists Docker images.
    • remove_image: Removes a Docker image.
    • push_image: Pushes a Docker image to a registry.
  • Container Management:
    • create_container: Creates a new Docker container.
    • stop_container: Stops a running Docker container.
    • list_containers: Lists all Docker containers.
    • remove_container: Removes a Docker container.
    • commit_container: Commits changes in a container to create a new image.

Configuration

The module can be configured via environment variables to change the Docker API endpoint and the Unix socket path. If these environment variables are not set, defaults are used.

Notes

  • Ensure that the Docker Engine is accessible and that appropriate permissions are set for the Unix socket or API endpoint.
  • The module is intended for use with standard Docker installations, but it can also interact with other container management systems like Podman, provided they are compatible with the Docker API.
source