Skip to content

Commit c70dd80

Browse files
Merge pull request #92 from testcontainers/feature/78-local-image-fallback
Support locally built images with Docker::Image.get before pull
2 parents 849875c + 9dbb414 commit c70dd80

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

core/lib/testcontainers/docker_container.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,18 @@ def start
487487

488488
connection = Docker::Connection.new(Docker.url, Docker.options)
489489

490-
Docker::Image.create({"fromImage" => @image}.merge(@image_create_options), connection)
490+
image_options = {"fromImage" => @image}.merge(@image_create_options)
491+
image_reference = (image_options["fromImage"] || image_options[:fromImage] || @image).to_s
492+
tag_option = image_options["tag"] || image_options[:tag]
493+
if tag_option && !image_reference.end_with?(":#{tag_option}")
494+
image_reference = "#{image_reference}:#{tag_option}"
495+
end
496+
497+
begin
498+
Docker::Image.get(image_reference, {}, connection)
499+
rescue Docker::Error::NotFoundError
500+
Docker::Image.create(image_options, connection)
501+
end
491502

492503
@_container ||= Docker::Container.create(_container_create_options)
493504
@_container.start

core/test/docker_container_test.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# frozen_string_literal: true
22

33
require "test_helper"
4+
require "tmpdir"
5+
require "securerandom"
46

57
class DockerContainerTest < TestcontainersTest
68
def before_all
@@ -44,6 +46,38 @@ def test_it_creates_an_image_with_options
4446
bad_container.remove if bad_container.exists?
4547
end
4648

49+
def test_it_uses_locally_built_image_before_pulling
50+
image_repo = "testcontainers-local-#{SecureRandom.hex(6)}"
51+
image_tag = "latest"
52+
image_reference = "#{image_repo}:#{image_tag}"
53+
container = nil
54+
55+
Dir.mktmpdir do |dir|
56+
dockerfile_path = File.join(dir, "Dockerfile")
57+
File.write(dockerfile_path, <<~DOCKERFILE)
58+
FROM alpine:latest
59+
CMD ["sleep", "60"]
60+
DOCKERFILE
61+
62+
Docker::Image.build_from_dir(dir, {"t" => image_reference, "dockerfile" => "Dockerfile"})
63+
end
64+
65+
container = Testcontainers::DockerContainer.new(image_reference)
66+
container.start
67+
68+
assert container.running?
69+
ensure
70+
if container
71+
container.stop if container.running?
72+
container.remove if container.exists?
73+
end
74+
begin
75+
Docker::Image.get(image_reference).remove(force: true)
76+
rescue Docker::Error::NotFoundError
77+
# image already removed
78+
end
79+
end
80+
4781
def test_it_returns_the_container_image
4882
assert_equal "hello-world", @container.image
4983
end

0 commit comments

Comments
 (0)