### Install Docker API Gem - Bundle Install Source: https://github.com/upserve/docker-api/blob/master/README.md This shell command installs dependencies listed in the Gemfile, including the docker-api gem. It depends on Bundler and a Gemfile with the gem added. Inputs include the Gemfile; outputs confirm successful installation. Limitations include requiring internet access and proper Ruby/Bundler setup. ```shell $ bundle install ``` -------------------------------- ### Create and start Docker containers (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt Create a container from an image with command and options, then start it. Supports naming, exposed ports, and arbitrary configuration. Requires the docker gem. ```ruby require 'docker' # Create simple container container = Docker::Container.create( 'Image' => 'ubuntu:20.04', 'Cmd' => ['bash', '-c', 'while true; do date; sleep 1; done'] ) # Start container container.start # Create with name container = Docker::Container.create( 'name' => 'my-web-app', 'Image' => 'nginx:alpine', 'ExposedPorts' => {'80/tcp' => {}} ) ``` -------------------------------- ### Create and Execute Docker Exec in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This example covers creating exec instances in containers and starting them to run commands like 'ps aux', capturing stdout, stderr, and exit code. Depends on 'docker' gem and existing container. Inputs: container ID, command array, attach flags; outputs: exec ID and command results. Limitations: Exec requires container to be running. ```ruby require 'docker' container = Docker::Container.get('my-app') # Create exec instance exec_instance = Docker::Exec.create({ 'Container' => container.id, 'Cmd' => ['ps', 'aux'], 'AttachStdout' => true, 'AttachStderr' => true }, Docker.connection) # => Docker::Exec { :id => 3f2e1d4c... } # Execute and capture output stdout, stderr, exit_code = exec_instance.start! puts stdout.join # Output: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND # root 1 0.0 0.1 18236 3384 ? Ss 10:30 0:00 nginx # => [["USER PID..."], [], 0] ``` -------------------------------- ### Start Docker Daemon Source: https://github.com/upserve/docker-api/blob/master/README.md This shell command starts the Docker daemon for remote API calls. It requires Docker installed on the system and sudo privileges. No inputs; outputs include daemon starting confirmation. Limitations include root access and ongoing daemon process. ```shell $ sudo docker -d ``` -------------------------------- ### Install Docker API Gem - Direct Install Source: https://github.com/upserve/docker-api/blob/master/README.md This shell command directly installs the docker-api gem using RubyGems. It requires RubyGems (part of Ruby). No specific inputs; outputs include installed gem. Limitations are internet access and RubyGems configuration; suitable for scripts or environments without Bundler. ```shell $ gem install docker-api ``` -------------------------------- ### Create Docker containers with port binding and volume mounts Source: https://context7.com/upserve/docker-api/llms.txt Creates Docker containers with specific configurations including port mappings and volume mounts. The first example maps container port 80 to host port 8080 for an nginx container. The second example creates a PostgreSQL container with environment variables and volume bindings. Requires the docker-api gem. ```ruby container = Docker::Container.create( 'Image' => 'nginx:alpine', 'ExposedPorts' => {'80/tcp' => {}}, 'HostConfig' => { 'PortBindings' => { '80/tcp' => [{'HostPort' => '8080'}] } } ) container.start # => Docker::Container { :id => 9f2e1d3c... } # Create with volume mount container = Docker::Container.create( 'Image' => 'postgres:13', 'Env' => ['POSTGRES_PASSWORD=secret'], 'HostConfig' => { 'Binds' => ['/host/data:/var/lib/postgresql/data'] } ) container.start # => Docker::Container { :id => 5d4c3b2a... } ``` -------------------------------- ### Start Docker container Source: https://github.com/upserve/docker-api/blob/master/README.md Starts a Docker container that has been created but is not currently running. Returns a Docker::Container object with connection details. Requires an existing container object. ```ruby container.start ``` -------------------------------- ### Pull Docker Image in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This example shows how to pull a Docker image using the docker-api gem, including options for progress monitoring. ```ruby require 'docker' # Pull Ubuntu 14.04 image image = Docker::Image.create('fromImage' => 'ubuntu', 'tag' => '14.04') # => Docker::Image { :id => ae7ffbcd1a3c... } # Pull image with progress monitoring image = Docker::Image.create('fromImage' => 'nginx', 'tag' => 'latest') do |chunk| progress = JSON.parse(chunk) puts "Status: #{progress['status']}, Progress: #{progress['progress']}" if progress['progress'] end # => Docker::Image { :id => 605c77e624dd... } ``` -------------------------------- ### Install Docker API Gem - Add to Gemfile Source: https://github.com/upserve/docker-api/blob/master/README.md This code snippet demonstrates adding the docker-api gem to a Ruby application's Gemfile for dependency management. It requires a Ruby environment with Bundler installed. The output is an updated Gemfile; no specific inputs beyond the gem name are needed, and it has no limitations beyond standard Ruby gemfile syntax. ```ruby gem 'docker-api' ``` -------------------------------- ### Create and Manage Docker Volumes in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This example shows creating volumes with default or custom drivers like NFS, listing volumes, mounting them in containers, and pruning unused ones. Depends on 'docker' gem and Docker daemon. Inputs: volume name and options such as driver opts and labels; outputs: Docker::Volume objects. Limitations: Volumes in use cannot be removed directly. ```ruby require 'docker' # Create volume with default driver volume = Docker::Volume.create('my-data') # => Docker::Volume { :id => my-data... } # Create with driver options volume = Docker::Volume.create('nfs-data', { 'Driver' => 'local', 'DriverOpts' => { 'type' => 'nfs', 'o' => 'addr=192.168.1.1,rw', 'device' => ':/path/to/dir' }, 'Labels' => { 'environment' => 'production' } }) # => Docker::Volume { :id => nfs-data... } # List all volumes volumes = Docker::Volume.all # => [Docker::Volume { :id => my-data... }] # Get specific volume volume = Docker::Volume.get('my-data') # => Docker::Volume { :id => my-data... } # Use volume in container container = Docker::Container.create( 'Image' => 'postgres:13', 'HostConfig' => { 'Binds' => ["my-data:/var/lib/postgresql/data"] } ) # => Docker::Container { :id => 7a3b2c1d... } # Remove volume volume.remove # => nil # Prune unused volumes Docker::Volume.prune # => {"VolumesDeleted"=>["unused-volume"], "SpaceReclaimed"=>1258291200} ``` -------------------------------- ### Execute Container Command Detached (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt This example shows how to execute a command within a Docker container in detached mode. Using detach: true ensures that the execution continues in the background, allowing you to perform other operations. The start! method returns nil when run detached. ```ruby exec_instance = Docker::Exec.create({ 'Container' => container.id, 'Cmd' => ['bash', '-c', 'sleep 30 && echo done'], 'AttachStdout' => true, 'AttachStderr' => true }, Docker.connection) exec_instance.start!(detach: true) # => nil ``` -------------------------------- ### Create container with port bindings Source: https://github.com/upserve/docker-api/blob/master/README.md Creates Docker containers with various port binding configurations. Examples include exposing ports to bridge, specifying host ports, and binding to specific IPs. Requires valid image name. ```ruby Docker::Container.create( 'Image' => 'image-name', 'HostConfig' => { 'PortBindings' => { '1234/tcp' => [{}] } } ) ``` ```ruby Docker::Container.create( 'Image' => 'image-name', 'ExposedPorts' => { '1234/tcp' => {} }, 'HostConfig' => { 'PortBindings' => { '1234/tcp' => [{}] } } ) ``` ```ruby Docker::Container.create( 'Image' => 'image-name', 'ExposedPorts' => { '1234/tcp' => {} }, 'HostConfig' => { 'PortBindings' => { '1234/tcp' => [{ 'HostPort' => '1234' }] } } ) ``` ```ruby Docker::Container.create( 'Image' => 'image-name', 'ExposedPorts' => { '1234/tcp' => {} }, 'HostConfig' => { 'PortBindings' => { '1234/tcp' => [{ 'HostPort' => '1234', 'HostIp' => '192.168.99.100' }] } } ) ``` -------------------------------- ### Connect to Multiple Docker Hosts (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt This example showcases how to connect to multiple Docker hosts, both local and remote. It demonstrates the creation of custom Docker::Connection objects with different host addresses and options, such as read and write timeouts. These connections can then be used to manage containers and images on each host. ```ruby require 'docker' # Create custom connections local_conn = Docker::Connection.new('unix:///var/run/docker.sock', {}) remote_conn = Docker::Connection.new('tcp://remote.example.com:2375', { read_timeout: 300, write_timeout: 300 }) # Use connections for specific operations local_containers = Docker::Container.all({}, local_conn) # => [Docker::Container { :id => 7a3b2c1d... }] remote_images = Docker::Image.all({}, remote_conn) # => [Docker::Image { :id => ae7ffbcd... }] # Create container on remote host container = Docker::Container.create({ 'Image' => 'nginx:alpine', 'name' => 'remote-nginx' }, remote_conn) # => Docker::Container { :id => 9f2e1d3c... } # Check if remote is Podman remote_conn.podman? # => false # Get remote daemon info remote_conn.info # => {"Containers"=>15, "Images"=>32, "ServerVersion"=>"20.10.7"} ``` -------------------------------- ### Create and Tag Docker Image using Rake Source: https://github.com/upserve/docker-api/blob/master/README.md Provides a Rake task DSL for creating and managing Docker images. This example shows how to define a task to create an image from a base image, commit changes, and tag it. It also demonstrates tagging an existing image with a new tag. ```ruby require 'rake' require 'docker' image 'repo:tag' do image = Docker::Image.create('fromImage' => 'repo', 'tag' => 'old_tag') image = Docker::Image.run('rm -rf /etc').commit image.tag('repo' => 'repo', 'tag' => 'tag') end image 'repo:new_tag' => 'repo:tag' do image = Docker::Image.create('fromImage' => 'repo', 'tag' => 'tag') image = image.insert_local('localPath' => 'some-file.tar.gz', 'outputPath' => '/') image.tag('repo' => 'repo', 'tag' => 'new_tag') end ``` -------------------------------- ### Check Exec Status and Wait for Completion (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt Demonstrates how to check the status of an executing command and wait for its completion. The example retrieves the execution's JSON information, checks its 'Running' status and 'ExitCode', and uses sleep to simulate waiting for termination. ```ruby info = exec_instance.json # => {"ID"=>"3f2e1d4c...", "Running"=>true, "ExitCode"=>null, "Pid"=>54321} sleep 31 info = exec_instance.json # => {"ID"=>"3f2e1d4c...", "Running"=>false, "ExitCode"=>0, "Pid"=>54321} ``` -------------------------------- ### List and inspect Docker containers with filters Source: https://context7.com/upserve/docker-api/llms.txt Lists Docker containers with various filtering options and retrieves detailed container information. Supports filtering by status, labels, and other criteria. Also provides methods for refreshing container information to get the latest state. Requires the docker-api gem. ```ruby require 'docker' # List running containers containers = Docker::Container.all # => [Docker::Container { :id => 7a3b2c1d... }] # List all containers (including stopped) all_containers = Docker::Container.all('all' => true) # => [Docker::Container { :id => 7a3b2c1d... }, Docker::Container { :id => 5d4c3b2a... }] # List with filters (only exited containers) exited = Docker::Container.all( 'all' => true, 'filters' => {'status' => ['exited']}.to_json ) # => [Docker::Container { :id => 2e1f3d4c... }] # List by label labeled = Docker::Container.all( 'all' => true, 'filters' => {'label' => ['environment=production']}.to_json ) # => [Docker::Container { :id => 8f7e6d5c... }] # Get container by ID or name container = Docker::Container.get('my-web-app') # => Docker::Container { :id => 7a3b2c1d4e5f... } # Get detailed container information info = container.json # => {"Id"=>"7a3b2c1d4e5f...", # "Created"=>"2021-05-15T10:30:00Z", # "State"=>{"Status"=>"running", "Running"=>true, "Pid"=>12345}, # "Config"=>{"Image"=>"nginx:alpine", "Cmd"=>["nginx", "-g", "daemon off;"]}, # "NetworkSettings"=>{"IPAddress"=>"172.17.0.2", "Ports"=>{"80/tcp"=>[{"HostPort"=>"8080"}]}}} # Refresh container info (get latest state) container.refresh! # => Docker::Container { :id => 7a3b2c1d... } ``` -------------------------------- ### Stream Docker Events in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This snippet illustrates streaming real-time Docker events with filters, timeouts, and parsing attributes for actions like container start or die. Requires 'docker' gem. Inputs: filters for type/event, timeout, since timestamp; outputs: event objects processed in block. Limitations: Streams block indefinitely unless broken manually or timed out. ```ruby require 'docker' # Stream all events (blocks indefinitely) Docker::Event.stream(read_timeout: 0) do |event| puts "#{event.type} #{event.action} - #{event.actor.id}" break if some_condition # Must break manually end # Output: container start - 7a3b2c1d4e5f... # container die - 5d4c3b2a1f6e... # image pull - nginx:alpine # => nil # Stream events with filters Docker::Event.stream( read_timeout: 0, filters: { type: ['container'], event: ['start', 'stop'] }.to_json ) do |event| timestamp = Time.at(event.time) puts "[#{timestamp}] Container #{event.actor.id[0..11]} #{event.action}" end # Output: [2021-05-15 10:30:00] Container 7a3b2c1d4e5f start # [2021-05-15 10:31:15] Container 7a3b2c1d4e5f stop # Stream events since timestamp Docker::Event.since(Time.now.to_i - 3600) do |event| puts "#{event.type}: #{event.status} - #{event.from} (#{event.id[0..11]})") end # Output: container: create - ubuntu:20.04 (492510dd38e4) # container: start - ubuntu:20.04 (492510dd38e4) # => nil # Parse event attributes Docker::Event.stream(read_timeout: 60) do |event| case event.action when 'start' puts "Container #{event.actor.attributes['name']} started" when 'die' exit_code = event.actor.attributes['exitCode'] puts "Container exited with code #{exit_code}" when 'health_status' status = event.actor.attributes['health_status'] puts "Health check: #{status}" end break if event.action == 'die' end # Output: Container my-web-app started # Health check: healthy ``` -------------------------------- ### Get running processes in container in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Lists the running processes inside a Docker container. Useful for debugging and process management. Requires a running container instance. ```ruby processes = container.top ``` -------------------------------- ### GET /container/{id} Source: https://github.com/upserve/docker-api/blob/master/README.md Get detailed information about a specific container by ID or name. ```APIDOC ## GET /container/{id} ### Description Get detailed information about a specific container by ID or name. ### Method GET ### Endpoint /container/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Container ID or name ### Request Example GET /container/500f53b25e6e ### Response #### Success Response (200) - **id** (string) - Container ID - **connection** (object) - Connection details #### Response Example { "id": "500f53b25e6e", "connection": { "url": "tcp://localhost", "options": { "port": 2375 } } } ``` -------------------------------- ### Configure SSL Options in Ruby - File Paths Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code configures SSL options for Docker using file paths. It requires docker-api gem, OpenSSL, and cert files. Inputs include cert path; outputs set options. Limitations include specific file names and SSL setup. ```ruby Docker.options = { client_cert: File.join(cert_path, 'cert.pem'), client_key: File.join(cert_path, 'key.pem'), ssl_ca_file: File.join(cert_path, 'ca.pem'), scheme: 'https' } ``` -------------------------------- ### Handle Docker API Errors (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt This example illustrates how to handle various Docker API errors in a Ruby application. It demonstrates rescuing specific error types (NotFoundError, ConflictError, AuthenticationError, TimeoutError, ServerError) and provides appropriate error messages or recovery actions. ```ruby require 'docker' begin # Attempt to get non-existent container container = Docker::Container.get('nonexistent') rescue Docker::Error::NotFoundError => e puts "Container not found: #{e.message}" # Output: Container not found: No such container: nonexistent end begin # Try to remove image in use image = Docker::Image.get('nginx:alpine') image.remove rescue Docker::Error::ConflictError => e puts "Cannot remove: #{e.message}" # Force remove image.remove('force' => true) end begin # Authentication failure Docker.authenticate!('username' => 'wrong', 'password' => 'invalid') rescue Docker::Error::AuthenticationError => e puts "Login failed: #{e.message}" end begin # Timeout on long operation container = Docker::Container.create('Image' => 'ubuntu', 'Cmd' => ['sleep', '1000']) container.start container.wait(5) # Timeout after 5 seconds rescue Docker::Error::TimeoutError => e puts "Operation timed out: #{e.message}" container.kill end begin # Server error Docker::Container.create('Image' => 'invalid::image::name') rescue Docker::Error::ServerError => e puts "Server error: #{e.message}" rescue Docker::Error::ClientError => e puts "Client error: #{e.message}" ``` -------------------------------- ### Get filesystem changes in container in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Retrieves changes made to the container's filesystem. Useful for auditing and debugging. Requires a running container instance. ```ruby changes = container.changes ``` -------------------------------- ### Execute Container Command with TTY (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt This snippet demonstrates how to execute a command within a Docker container with a TTY attached. It uses the Docker::Exec API to create and start an execution session, capturing standard output. This is useful for interactive sessions or when you need to see the output of the command in real-time. ```ruby exec_instance = Docker::Exec.create({ 'Container' => container.id, 'Cmd' => ['bash', '-c', 'echo -e \"Line1\nLine2\"'], 'AttachStdout' => true, 'Tty' => true }, Docker.connection) stdout, stderr, status = exec_instance.start!(tty: true) # => [["Line1\nLine2\n"], [], 0] ``` -------------------------------- ### Restart Docker container Source: https://github.com/upserve/docker-api/blob/master/README.md Restarts a Docker container by stopping and then starting it. Returns a Docker::Container object with connection details. Useful for applying configuration changes. ```ruby container.restart ``` -------------------------------- ### Get container information in JSON format Source: https://github.com/upserve/docker-api/blob/master/README.md Retrieves detailed information about a Docker container in JSON format. This includes container ID, creation time, configuration, state, and network settings. No additional dependencies required. ```ruby container.json ``` -------------------------------- ### Get container process information Source: https://github.com/upserve/docker-api/blob/master/README.md Returns information about currently executing processes in a container. Can return data in array format or as a hash with titles and processes. Container must be running. ```ruby container.top ``` ```ruby container.top(format: :hash) ``` -------------------------------- ### Get container logs with timestamps in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Retrieves the last 100 logs from a Docker container with timestamps. Useful for debugging and monitoring container activity. Requires a running container instance. ```ruby logs = container.logs(stdout: true, timestamps: true, tail: 100) ``` -------------------------------- ### Get container resource statistics in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Retrieves resource usage statistics for a Docker container, including CPU, memory, and network metrics. Useful for monitoring container performance. Requires a running container instance. ```ruby stats = container.stats ``` -------------------------------- ### Get Docker Image by ID (Ruby) Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code fetches a specific Docker image by its ID from the server. It requires the 'docker' gem and the image ID as a string. The method returns a Docker::Image object, equivalent to 'docker images '. ```ruby Docker::Image.get('df4f1bdecf40') ``` -------------------------------- ### Tag and Push Docker Image in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This snippet demonstrates how to tag an existing Docker image and push it to a registry using the docker-api gem, including authentication and progress monitoring. ```ruby require 'docker' # Get existing image image = Docker::Image.get('nginx:latest') # Tag image with repository name image.tag('repo' => 'myregistry.com/webapp', 'tag' => 'v1.0', 'force' => true) # => ["myregistry.com/webapp:v1.0"] # Authenticate with registry Docker.authenticate!( 'username' => 'deployer', 'password' => 'secret', 'serveraddress' => 'https://myregistry.com' ) # Push image to registry image.push(nil, repo_tag: 'myregistry.com/webapp:v1.0') do |chunk| progress = JSON.parse(chunk) puts "#{progress['status']}: #{progress['progress']}" if progress['status'] end # Output: Preparing: ``` -------------------------------- ### GET /container Source: https://github.com/upserve/docker-api/blob/master/README.md List containers with optional filtering. By default only returns running containers. ```APIDOC ## GET /container ### Description List containers with optional filtering. By default only returns running containers. ### Method GET ### Endpoint /container ### Parameters #### Query Parameters - **all** (boolean) - Optional - Return all containers (default: false) - **filters** (string) - Optional - JSON encoded filter parameters (status, label) ### Request Example GET /container?all=true&filters={"status":["exited"]} ### Response #### Success Response (200) - **containers** (array) - Array of container objects #### Response Example [ { "id": "500f53b25e6e", "connection": { "url": "tcp://localhost", "options": { "port": 2375 } } } ] ``` -------------------------------- ### Create and Manage Docker Networks in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This snippet demonstrates creating bridge networks with optional IPAM configuration, listing and retrieving network details, connecting/disconnecting containers, and pruning unused networks. It requires the 'docker' gem and a running Docker daemon. Inputs include network name and options like driver and subnet; outputs are Docker::Network objects or lists. Limitations: Networks must not be in use for removal. ```ruby # Create bridge network network = Docker::Network.create('my-network', { 'Driver' => 'bridge', 'CheckDuplicate' => true }) # => Docker::Network { :id => 8f3e2d1c... } # Create with IPAM configuration network = Docker::Network.create('app-network', { 'Driver' => 'bridge', 'IPAM' => { 'Config' => [ { 'Subnet' => '172.20.0.0/16', 'Gateway' => '172.20.0.1' } ] }, 'Options' => { 'com.docker.network.bridge.name' => 'app-bridge' } }) # => Docker::Network { :id => 5d4c3b2a... } # List all networks networks = Docker::Network.all # => [Docker::Network { :id => 8f3e2d1c... }] # Get specific network network = Docker::Network.get('my-network') # => Docker::Network { :id => 8f3e2d1c... } # Get network details details = network.json # => {"Id"=>"8f3e2d1c...", # "Name"=>"my-network", # "Driver"=>"bridge", # "Scope"=>"local", # "Containers"=>{}} # Connect container to network container = Docker::Container.get('my-app') network.connect(container.id, {}, {'IPAMConfig' => {'IPv4Address' => '172.20.0.10'}}) # => Docker::Network { :id => 8f3e2d1c... } # Disconnect container from network network.disconnect(container.id) # => Docker::Network { :id => 8f3e2d1c... } # Remove network network.remove # => nil # Prune unused networks Docker::Network.prune # => {"NetworksDeleted"=>["old-network"], "SpaceReclaimed"=>0} ``` -------------------------------- ### GET /events Source: https://github.com/upserve/docker-api/blob/master/README.md Stream Docker events in real-time or retrieve events since a specific timestamp. ```APIDOC ## GET /events ### Description Stream Docker events in real-time or retrieve events since a specific timestamp. ### Method GET ### Endpoint /events ### Parameters #### Query Parameters - **since** (integer) - Optional - Timestamp to start retrieving events from - **read_timeout** (integer) - Optional - Read timeout in seconds (0 for no timeout) ### Request Example GET /events?since=1416958763 ### Response #### Success Response (200) - **status** (string) - Event status (create, die, etc.) - **id** (string) - Container ID - **from** (string) - Source image - **time** (integer) - Event timestamp #### Response Example { "status": "create", "id": "aeb8b55726df63bdd69d41e1b2650131d7ce32ca0d2fa5cbc75f24d0df34c7b0", "from": "base:latest", "time": 1416958554 } ``` -------------------------------- ### Configure Docker Connection in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This snippet demonstrates how to configure the Docker connection URL and SSL/TLS options using the docker-api gem. It also shows how to authenticate with a Docker registry and retrieve basic Docker information. ```ruby require 'docker' # Set Docker daemon URL Docker.url = 'tcp://example.com:2375' # Configure SSL/TLS options Docker.options = { client_cert: File.join('/certs', 'cert.pem'), client_key: File.join('/certs', 'key.pem'), ssl_ca_file: File.join('/certs', 'ca.pem'), scheme: 'https' } # Get Docker version information version_info = Docker.version # => {"Version":"20.10.7", "ApiVersion":"1.41", "GoVersion":"go1.16.4"} # Get Docker daemon information info = Docker.info # => {"Containers":10, "Images":45, "Driver":"overlay2", "MemoryLimit":true} # Ping Docker daemon Docker.ping # => "OK" # Check if connected to Podman instead of Docker Docker.podman? # => false # Authenticate with Docker registry Docker.authenticate!( 'username' => 'myuser', 'password' => 'mypass', 'email' => 'user@example.com', 'serveraddress' => 'https://registry.gitlab.com/v1/' ) # => true ``` -------------------------------- ### Build Docker Image from Directory in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This shows how to build a Docker image from a directory (containing a Dockerfile) using the docker-api gem, with custom Dockerfile names and streaming logs. ```ruby require 'docker' # Build from current directory (uses Dockerfile) image = Docker::Image.build_from_dir('.') # => Docker::Image { :id => 1266dc19e8f7... } # Build with custom Dockerfile name image = Docker::Image.build_from_dir('.', { 'dockerfile' => 'Dockerfile.production', 't' => 'myapp:v1.0' }) # => Docker::Image { :id => 9a3d5b2c... } # Build with streaming logs Docker::Image.build_from_dir('.', {'t' => 'webapp:latest'}) do |chunk| begin log = JSON.parse(chunk) puts log['stream'] if log['stream'] rescue JSON::ParserError # Ignore malformed JSON chunks end end # Output: Successfully built 7f3a2e1d9c8b # Successfully tagged webapp:latest # => Docker::Image { :id => 7f3a2e1d9c8b... } ``` -------------------------------- ### Build Docker Image in Ruby Source: https://github.com/upserve/docker-api/blob/master/README.md Demonstrates building Docker images from Dockerfile strings or directories using Ruby. Returns a new Docker::Image object with the built image. ```ruby Docker::Image.build("from base\nrun touch /test") Docker::Image.build_from_dir('.') ``` -------------------------------- ### Get Container by ID or Name Source: https://github.com/upserve/docker-api/blob/master/README.md Retrieves a specific Docker container using its ID or name. This class method returns a `Docker::Container` object representing the requested container. ```ruby Docker::Container.get('500f53b25e6e') # => Docker::Container { :id => , :connection => Docker::Connection { :url => tcp://localhost, :options => {:port=>2375} } } ``` -------------------------------- ### Update Container Configuration Source: https://github.com/upserve/docker-api/blob/master/README.md Updates the configuration of a Docker container. This method accepts a hash of attributes to modify, such as CPU shares. The example shows increasing the CPU shares for a container. ```ruby container.update("CpuShares" => 50000") ``` -------------------------------- ### Build Docker Image from String in Ruby Source: https://context7.com/upserve/docker-api/llms.txt This snippet demonstrates building a Docker image from a Dockerfile string using the docker-api gem, with and without streaming output. ```ruby require 'docker' # Build image from Dockerfile content dockerfile = <<-DOCKERFILE FROM ubuntu:14.04 RUN apt-get update && apt-get install -y curl RUN echo "Hello from Docker" > /hello.txt WORKDIR /app CMD ["bash"] DOCKERFILE image = Docker::Image.build(dockerfile) # => Docker::Image { :id => b750fe79269d... } # Build with streaming output image = Docker::Image.build(dockerfile) do |chunk| log = JSON.parse(chunk) puts log['stream'] if log.has_key?('stream') end # Output: Step 1/5 : FROM ubuntu:14.04 # Step 2/5 : RUN apt-get update... # => Docker::Image { :id => 8f3d2a1b... } ``` -------------------------------- ### Execute Global Docker API Calls in Ruby Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code demonstrates global Docker API calls like version, info, and authenticate. It requires docker-api gem and Docker connection. No inputs needed for calls; outputs return API data. Limitations include API availability and permissions. ```ruby require 'docker' # => true # docker command for reference: docker version Docker.version # => { 'Version' => '0.5.2', 'GoVersion' => 'go1.1' } # docker command for reference: docker info Docker.info # => { "Debug" => false, "Containers" => 187, "Images" => 196, "NFd" => 10, "NGoroutines" => 9, "MemoryLimit" => true } # docker command for reference: docker login Docker.authenticate!('username' => 'docker-fan-boi', 'password' => 'i<3docker', 'email' => 'dockerboy22@aol.com') # => true # docker command for reference: docker login registry.gitlab.com Docker.authenticate!('username' => 'docker-fan-boi', 'password' => 'i<3docker', 'email' => 'dockerboy22@aol.com', 'serveraddress' => 'https://registry.gitlab.com/v1/') # => true ``` -------------------------------- ### Get Docker Container Statistics Source: https://github.com/upserve/docker-api/blob/master/README.md Retrieves current runtime statistics for a container including CPU, memory, network, and I/O metrics. Returns a detailed hash with timestamped statistical data about container performance. ```ruby container.stats # => {"read"=>"2016-02-29T20:47:05.221608695Z", "precpu_stats"=>{"cpu_usage"=> ... } ``` -------------------------------- ### Push Docker Image in Ruby Source: https://github.com/upserve/docker-api/blob/master/README.md Shows how to push Docker images to a registry using Ruby. Requires prior authentication and tagging. Supports pushing specific tags or full repository tags. ```ruby image.push image.push(nil, tag: "tag_name") image.push(nil, repo_tag: 'registry/repo_name:tag_name') ``` -------------------------------- ### Export container filesystem as tar in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Exports the entire filesystem of a Docker container as a tar archive. Useful for backup and migration. Requires a container instance. ```ruby File.open('/tmp/container-export.tar', 'wb') do |file| container.export { |chunk| file.write(chunk) } end ``` -------------------------------- ### Get Events Since a Specific Time Source: https://github.com/upserve/docker-api/blob/master/README.md Retrieves all Docker events that have occurred since a specified Unix timestamp. The method also waits for and processes any new events that arrive after the initial retrieval. A block can be provided to handle each event. ```ruby require 'docker' # Action on all events after a given time (will execute the block for all events up till the current time, and wait to execute on any new events after) Docker::Event.since(1416958763) { |event| puts event; puts Time.now.to_i; break } Docker::Event { :status => die, :id => 663005cdeb56f50177c395a817dbc8bdcfbdfbdaef329043b409ecb97fb68d7e, :from => base:latest, :time => 1416958764 } 1416959041 # => nil ``` -------------------------------- ### Connect to Multiple Docker Servers Source: https://github.com/upserve/docker-api/blob/master/README.md Demonstrates how to connect to different Docker servers. By default, all Docker objects use the connection specified by `Docker.connection`. To connect to multiple servers, a `Docker::Connection` object can be explicitly provided when calling class methods or initializing objects. ```ruby require 'docker' Docker::Container.all({}, Docker::Connection.new('tcp://example.com:2375', {})) ``` -------------------------------- ### Commit container with repository and tag in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Creates a new Docker image from a container with repository and tag. Useful for versioning. Requires a container instance and commit options. ```ruby image = container.commit( 'repo' => 'myapp', 'tag' => 'v1.0', 'comment' => 'Added application files', 'author' => 'deployer@example.com' ) ``` -------------------------------- ### Build Docker Images with Rake (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt This snippet demonstrates how to integrate Docker image building into a Rake task. It defines Rake tasks for building different image versions, using Docker::Image to create, modify, tag, and commit images. Dependencies between tasks are also illustrated. ```ruby # Rakefile require 'rake' require 'docker' # Simple image build task image 'myapp:latest' do image = Docker::Image.create('fromImage' => 'ruby', 'tag' => '3.0') image = image.run('gem install sinatra').commit image.tag('repo' => 'myapp', 'tag' => 'latest') end # Task with dependencies image 'myapp:production' => 'myapp:latest' do image = Docker::Image.create('fromImage' => 'myapp', 'tag' => 'latest') image = image.insert_local('localPath' => 'config/production.yml', 'outputPath' => '/app/config') image = image.run('bundle install --without development test').commit image.tag('repo' => 'myapp', 'tag' => 'production') end # Run with: rake myapp:production ``` -------------------------------- ### Run Command in Docker Image with Ruby Source: https://github.com/upserve/docker-api/blob/master/README.md Demonstrates running commands in a container created from an image using Ruby. Accepts command string as input, returns a Docker::Container object. ```ruby image.run('ls -l') ``` -------------------------------- ### Run command in a Docker image (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt Execute a command in a container created from the given image, optionally passing environment variables, working directory, and resource limits. Wait for completion and capture stdout/stderr. Requires the docker gem. ```ruby require 'docker' image = Docker::Image.get('ubuntu:20.04') # Run command in image (creates and starts container) container = image.run('ls -la /etc') # Run with options container = image.run(['bash', '-c', 'echo "Hello" > /tmp/test.txt'], { 'Env' => ['MY_VAR=value'], 'WorkingDir' => '/tmp', 'HostConfig' => { 'Memory' => 536870912 # 512MB } }) # Wait for container to finish and check output container.wait stdout, stderr = container.attach(stdout: true, stderr: true) puts stdout.join ``` -------------------------------- ### Pull Docker Image in Ruby Source: https://github.com/upserve/docker-api/blob/master/README.md Demonstrates how to pull a Docker image using the Ruby Docker API. Requires the 'docker' gem. Input is the image name and tag, output is a Docker::Image object. ```ruby require 'docker' image = Docker::Image.create('fromImage' => 'ubuntu:14.04') ``` -------------------------------- ### Attach to container with stdin in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Attaches to a Docker container with stdin for interactive commands. Useful for running commands inside containers. Requires a container instance and input data. ```ruby stdout, stderr = container.attach(stdin: StringIO.new("Hello\nWorld\n"), stdout: true) puts stdout.join ``` -------------------------------- ### Copy files into container in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Copies files into a Docker container from a tar stream. Useful for deployment and configuration. Requires a container instance and tar data. ```ruby tar_data = File.read('/tmp/upload.tar') container.archive_in(tar_data, '/app', 'noOverwriteDirNonDir' => 'true') ``` -------------------------------- ### Create Docker Container (Ruby) Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code creates a new Docker container from an image with specified commands. It requires the 'docker' gem and parameters like 'Cmd' and 'Image'. Returns a Docker::Container object, mapping to the Docker API containers endpoint. ```ruby require 'docker' container = Docker::Container.create('Cmd' => ['ls'], 'Image' => 'base') ``` -------------------------------- ### Stream container logs in real-time in Ruby Source: https://context7.com/upserve/docker-api/llms.txt Streams logs from a Docker container in real-time, with demultiplexing for stdout and stderr. Useful for live monitoring. Requires a running container instance and a block to handle the stream chunks. ```ruby container.streaming_logs(stdout: true, stderr: true, follow: true) do |stream, chunk| puts "[#{stream}] #{chunk}" end ``` -------------------------------- ### Save and load Docker images as tar archives (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt Save a single or multiple images to a tar file, retrieve raw binary data, stream to a custom handler, and load images from tar files or URLs. Use streaming for large images or custom pipelines. Requires the docker gem. ```ruby require 'docker' # Save single image to file image = Docker::Image.get('redis:6.2') image.save('/tmp/redis-6.2.tar') # Save image and get raw binary data binary_data = image.save # Stream image to custom handler image.save_stream do |chunk| # Write chunk to S3, network socket, etc. $stdout.write(chunk) end # Save multiple images to single tarball names = ['redis:6.2', 'postgres:13', 'nginx:alpine'] Docker::Image.save(names, '/tmp/multi-images.tar') # Load image from tar file Docker::Image.load('/tmp/redis-6.2.tar') # Load from file handle File.open('/tmp/redis-6.2.tar', 'rb') do |file| Docker::Image.load(file) end # Import image from tar or URL imported = Docker::Image.import('/tmp/container-export.tar') imported = Docker::Image.import('http://example.com/image.tar') # Import with streaming File.open('/tmp/export.tar', 'rb') do |file| Docker::Image.import_stream { file.read(4096).to_s } end ``` -------------------------------- ### Build Docker Image from Directory with Custom Dockerfile (Ruby) Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code builds a Docker image from the current directory using a specified Dockerfile (e.g., Dockerfile.Centos). It requires the 'docker' gem and a Docker connection. The method returns a Docker::Image object representing the built image. ```ruby Docker::Image.build_from_dir('.', { 'dockerfile' => 'Dockerfile.Centos' }) ``` -------------------------------- ### Build Docker Image from Tar File (Ruby) Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code builds a Docker image from a tar file. It requires the 'docker' gem and an open file object for the tar file. The method returns a Docker::Image object and is equivalent to the CLI command 'docker build - < docker_image.tar'. ```ruby Docker::Image.build_from_tar(File.open('docker_image.tar', 'r')) ``` -------------------------------- ### List, inspect, and remove Docker images (Ruby) Source: https://context7.com/upserve/docker-api/llms.txt List all images or filter by criteria, fetch detailed JSON and history, check existence, and remove images or prune unused ones. Supports filtering and force removal. Requires the docker gem. ```ruby require 'docker' # List all images images = Docker::Image.all # List with filters (only dangling images) dangling = Docker::Image.all('filters' => {'dangling' => ['true']}.to_json) # Get specific image by ID or tag image = Docker::Image.get('nginx:alpine') # Check if image exists Docker::Image.exist?('ubuntu:20.04') # Get detailed image information details = image.json # View image history (layers) history = image.history # Remove image image.remove('force' => true) # Remove unused images Docker::Image.prune ``` -------------------------------- ### Configure SSL Options in Ruby - ENV Data Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code configures SSL options for Docker using environment variables. It requires docker-api gem, ENV variables set, and OpenSSL. Inputs include ENV cert data; outputs set options. Limitations include loaded cert store and ENV variables. ```ruby cert_store = OpenSSL::X509::Store.new certificate = OpenSSL::X509::Certificate.new ENV["DOCKER_CA"] cert_store.add_cert certificate Docker.options = { client_cert_data: ENV["DOCKER_CERT"], client_key_data: ENV["DOCKER_KEY"], ssl_cert_store: cert_store, scheme: 'https' } ``` -------------------------------- ### Load Docker Image from File (Ruby) Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code loads a Docker image from a tar file on the filesystem. It accepts either a file path or an IO object. The method returns an empty string on success and requires the 'docker' gem. Two variants are shown for path and IO input. ```ruby Docker::Image.load('./my-image.tar') File.open('./my-image.tar', 'rb') do |file| Docker::Image.load(file) end ``` -------------------------------- ### Tag Docker Image in Ruby Source: https://github.com/upserve/docker-api/blob/master/README.md Illustrates tagging a Docker image with repository names and tags using Ruby. Supports force flag to overwrite existing tags. Returns the new tag as output. ```ruby image.tag('repo' => 'base2', 'force' => true) image.tag('repo' => 'base2', 'tag' => 'latest', force: true) ``` -------------------------------- ### List All Docker Images (Ruby) Source: https://github.com/upserve/docker-api/blob/master/README.md This Ruby code retrieves all Docker images available on the server. It uses the 'docker' gem and returns an array of Docker::Image objects. This is similar to the CLI command 'docker images'. ```ruby Docker::Image.all ``` -------------------------------- ### List All Containers Source: https://github.com/upserve/docker-api/blob/master/README.md Retrieves a list of all Docker containers on the host. By default, it only returns running containers. Passing `all: true` will include stopped and exited containers as well. The result is an array of `Docker::Container` objects. ```ruby Docker::Container.all(:all => true) # => [Docker::Container { :id => , :connection => Docker::Connection { :url => tcp://localhost, :options => {:port=>2375} } }] ```