docker-api Ruby Gem

repository·master·Indexed 22 days ago

https://github.com/upserve/docker-api

A Ruby gem providing an object-oriented interface to the Docker Engine API. It allows developers to programmatically manage containers, images, and registries. Key features include image building and pulling via Docker::Image, container lifecycle management via Docker::Container, event streaming, and support for SSL connections and remote Docker hosts.

Tokens
14K
Snippets
70
Records
75
Agent score
77%

What's inside docker-api

  1. Manage Docker Containers with Docker::Container

    master

    The Docker::Container class provides a one-to-one mapping to the Docker Remote API's Containers section. You cannot use .new to instantiate a container; instead, use Docker::Container.create to create a new instance. Once created, you can control the container lifecycle using methods like .start, .stop, .restart, .pause, .unpause, .kill, and .delete.

    require 'docker'
    
    # Create a Container
    container = Docker::Container.create('Cmd' => ['ls'], 'Image' => 'base')
    
    # Lifecycle management
    container.start
    container.stop
    container.restart
    container.pause
    container.unpause
    container.kill
    container.delete(:force => true)
  2. Manage Docker Images with Docker::Image

    master

    The Docker::Image class provides a Ruby interface for managing Docker images, mapping closely to the Docker Remote API.

    Important Note: Docker::Image.new is a private method. To obtain an instance of a Docker::Image, you must use factory methods such as .create, .build, .build_from_dir, .build_from_tar, or .import.

    Most methods accept an Hash of query parameters that correspond to the Docker API documentation.

    require 'docker'
    
    # Example: Pulling an image
    image = Docker::Image.create('fromImage' => 'ubuntu:14.04')
  3. Handle JSON encoded parameters

    master

    When passing parameters that the Docker API expects to be JSON encoded, docker-api does not perform implicit encoding. You must explicitly call .to_json on your parameter hash before passing it to the method call. This applies to all parameters requiring JSON encoding in the underlying Docker API.

    require 'docker'
    
    # Request all Containers, filtering by status 'exited'
    Docker::Container.all(all: true, filters: { status: ["exited"] }.to_json)
    
    # Request all Containers, filtering by label name
    Docker::Container.all(all: true, filters: { label: [ "label_name"  ]  }.to_json)
    
    # Request all Containers, filtering by label name and value
    Docker::Container.all(all: true, filters: { label: [ "label_name=label_value"  ]  }.to_json)
  4. Configure Docker Hub credentials for testing

    master

    Certain Rspec tests require Docker Hub credentials. To avoid hard-coding these into the codebase, the test suite uses the following environment variables. You must configure these in your shell profile or IDE:

    • DOCKER_API_USER: Your Docker Hub username.
    • DOCKER_API_PASS: Your Docker Hub password.
    • DOCKER_API_EMAIL: Your Docker Hub email address.
    export DOCKER_API_USER='your_docker_hub_user'
    export DOCKER_API_PASS='your_docker_hub_password'
    export DOCKER_API_EMAIL='your_docker_hub_email_address'
  5. Set up the development environment for docker-api

    master

    To develop on this gem, ensure you have a Ruby 1.9+ environment with bundler and Docker v1.3.1 or greater installed. Follow these steps to initialize the repository:

    1. Clone the repository: git clone git@github.com:upserve/docker-api.git
    2. Install dependencies: bundle install
    3. Create a feature branch: git checkout -b <branch_name>
    $ gem install bundler
    $ git clone git@github.com:upserve/docker-api.git
    $ bundle install
  6. Install the docker-api gem

    master

    You can install docker-api using Bundler by adding it to your Gemfile, or install it directly via the gem command for standalone scripts.

    To use the gem in a Ruby project, add require 'docker' to the top of your file.

    # In your Gemfile
    gem 'docker-api'
    # Install via Bundler
    $ bundle install
    
    # Or install directly
    $ gem install docker-api
  7. Run the docker-api test suite

    master

    You can run the tests using Rake. Depending on your needs, use one of the following commands:

    • bundle exec rake: Runs the full test suite.
    • rake rspec: Runs Rspec tests locally. Note that you must have all required base images pulled for this to work.
    • rake unpack: Pulls down all the required base images necessary for testing.

    If you are contributing changes, ensure tests pass before opening a Pull Request.

    # Run all tests
    bundle exec rake
    
    # Run Rspec specifically
    rake rspec
    
    # Pull required base images
    rake unpack
  8. Manage Docker Networks with Docker::Network

    master
    The Docker::Network class provides an interface for managing Docker networks, including creating, retrieving, deleting, and pruning them. You can interact with specific network instances or use class methods to perform global operations.
  9. Configure the Docker Host URL

    master

    By default, the gem assumes you are connecting to a local Docker socket. If you need to connect to a remote host or a specific port, you can set Docker.url.

    You can also configure the connection using the DOCKER_URL environment variable.

    Note: The gem uses excon for HTTP requests, so any options valid for Excon.new can be passed to Docker.options.

    # Set via Ruby
    Docker.url = 'tcp://example.com:5422'
    # Set via Environment Variable
    $ DOCKER_URL=unix:///var/docker.sock irb
  10. How Docker events and actors work

    master

    In docker-api, a Docker Event is a representation of a state change within the Docker daemon. When you call Docker::Event.stream, the library listens to the Docker event stream and instantiates Docker::Event objects for every incoming JSON message.

    Each event is linked to an Actor. The Actor is the specific object (like a container or a volume) that the event is about. The relationship is structured as follows:

    1. Event: Contains the type (what category of thing changed), the action (what happened), and the time.
    2. Actor: Nested within the event, the Actor contains the id and a hash of attributes that describe the specific entity involved.

    This hierarchy allows you to filter events by type and then drill down into the specific attributes of the entity that caused the change.

  11. Configure SSL for Docker connections

    master

    To use SSL, you can either set the DOCKER_CERT_PATH environment variable (pointing to a folder containing cert.pem, key.pem, and ca.pem) or configure Docker.options explicitly.

    If you need to load certificates from environment variables (e.g., on Heroku), you can pass the raw certificate data and an OpenSSL::X509::Store to Docker.options.

    # Explicit file-based configuration
    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'
    }
    # Loading from environment variables
    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'
    }
  12. Use the Rake DSL for image creation

    master

    A Rake DSL is provided to facilitate creating Docker images through Rake tasks. This allows you to define image build logic within a Rakefile.

    require 'rake'
    require 'docker'
    
    # Define a task to create an image
    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
    
    # Define a task with dependency logic
    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