Skip to content

Instantly share code, notes, and snippets.

@ch1ago
Created February 10, 2025 00:15
Show Gist options
  • Save ch1ago/1962929fd6d488bb48931ffb150501ae to your computer and use it in GitHub Desktop.
Save ch1ago/1962929fd6d488bb48931ffb150501ae to your computer and use it in GitHub Desktop.
# use case
DockerShell.start("kroki_service", "yuzutech/kroki", "9001", "8000") do
log stick :b, color, "I just think Ruby is the Best for coding!"
sleep 10
end
__BEGIN__
class MicroSystem::DockerShell < DevSystem::Shell
def self.start(container_name, image, host_port, container_port, &block)
new(container_name, image, host_port, container_port).start(&block)
end
def initialize(container_name, image, host_port, container_port)
sufix = Time.now.to_i
@container_name = "#{container_name}_#{sufix}"
@image = image
@host_port = host_port
@container_port = container_port
end
def start(&block)
Signal.trap("INT", &method(:interrupted))
_start
if block_given?
block.call
stop
else
log stick :b, :white, system.color, "Container #{@container_name} started."
end
end
def _start
string = "docker run -d -p#{@host_port}:#{@container_port} --name #{@container_name} #{@image}"
log stick :b, :white, system.color, "Starting container: #{@container_name}"
sh string
end
def stop
log stick :b, :white, system.color, "Stopping container: #{@container_name}"
sh "docker stop #{@container_name}"
log stick :b, :white, system.color, "Removing container: #{@container_name}"
sh "docker rm #{@container_name}"
rescue
log stick :red, "Failed to stop container #{@container_name}. Please check manually."
end
def interrupted(signo)
log stick :red, "Caught SIGINT (#{signo}), stopping container..."
stop
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment