Serverspec Workshop


Dockerfile testing

Let's say we want to test our Dockerfiles. Given a Dockerfile, ensure that ports are exposed and we have a specific CMD.

Installation

This is going to be more of an rspec style test and we also need another dependency:

NOTE: you may need to use sudo for installation of gems

NOTE: you may need the ruby development packages because this builds a native gem

gem install --no-ri --no-rdoc docker-api

Setup

First create a Dockerfile:

FROM ubuntu:14.04

EXPOSE 8000

CMD ["echo", "hi!"]

Now create our test file docker_spec.rb:

require 'docker'

describe "dockerfile built the image" do

  before(:all) do
    @image = Docker::Image.build_from_dir('.')
    p @image.json["Env"]
  end
 
  it "should exist" do
    expect(@image).not_to be_nil
  end
 
  it "should have CMD" do
    expect(@image.json["Config"]["Cmd"]).to include("echo")
  end

  it "should expose the default port" do
    expect(@image.json["Config"]["ExposedPorts"].has_key?("8000/tcp")).to be_truthy
  end
 
end

Finally run the spec:

rspec --format doc docker_spec.rb

specinfra is supposed to have docker backend support but it seems to be broken currently. If this were working, we could run real serverspec tests right against a real container, just just poke a the docker inspect json.

If our container had ssh setup, we could also ust the raw ssh backend for serverspec. This is outside the scope of this workshop.

Exercises