Skip to content

Instantly share code, notes, and snippets.

@idabmat
Created August 13, 2023 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idabmat/59e08ae6ddb1e169ff07494990d62f90 to your computer and use it in GitHub Desktop.
Save idabmat/59e08ae6ddb1e169ff07494990d62f90 to your computer and use it in GitHub Desktop.
dockerized PG
#!/bin/env ruby
require "thor"
require "json"
class PG < Thor
package_name "Dockerized PG"
include Thor::Actions
def self.exit_on_failure?
true
end
desc "up [VERSION] [PORT]", "Start latest or VERSION of a postgresql server on port 5432 or PORT."
def up(version = "latest", port = "5432")
say "Starting postgres version "
say version + " ", :magenta
say "on port "
say port, :yellow
run "docker run -d -p #{port}:5432 -l dockerized-postgresql -e POSTGRES_HOST_AUTH_METHOD=trust postgres:#{version}", capture: true, verbose: false
say "Started", :green
rescue SystemExit => e
say "Not started", :red
say "Is there a server already running on port #{port}?"
raise e
end
desc "down", "Stop postgresql server"
def down
instances = list_instances
return say "No instances running", :red if instances.length == 0
instances.each { |instance| stop_instance(instance) }
end
desc "status", "Shows the status of the postgresql server"
def status
instances = list_instances
return say "No instances running", :red if instances.length == 0
instances.each { |instance| print_instance(instance) }
end
private
def list_instances
`docker ps -f label=dockerized-postgresql --format json`
.split("\n")
.map { |line| JSON.parse(line) }
end
def print_instance(instance)
info = JSON.parse(`docker inspect #{instance["ID"]}`)
port = info.dig(0, "HostConfig", "PortBindings", "5432/tcp", 0, "HostPort")
status = info.dig(0, "State", "Status")
version = info.dig(0, "Config", "Image").split(":").last
say "Found version "
say version + " ", :magenta
say status + " on port "
say port, :yellow
end
def stop_instance(instance)
print_instance(instance)
return say "Skipping...", :yellow unless yes?("Stop it? [yN]")
`docker stop #{instance["ID"]}`
say "Stopped", :green
end
end
PG.start(ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment