Skip to content

Instantly share code, notes, and snippets.

@clicube
Last active August 29, 2015 14:25
Show Gist options
  • Save clicube/9fde23253d6303331fbf to your computer and use it in GitHub Desktop.
Save clicube/9fde23253d6303331fbf to your computer and use it in GitHub Desktop.
Dockerのコンテナを操作するRakefile
NAME = File.basename(File.dirname(__FILE__))
IMAGE = "#{ENV['USER']}/#{NAME}"
DIR = File.dirname(__FILE__)
DOCKER_OPT = ""
task "status" do
puts get_status
end
task "build" do
tag = "auto_" + Time.now.to_i.to_s
cstatus = get_status
if cstatus != "no-image"
sh "docker tag #{IMAGE}:latest #{IMAGE}:#{tag}"
end
sh "docker build --force-rm -t #{IMAGE}:latest #{DIR}" do |ok,status|
if cstatus != "no-image"
if ok
sh "docker rmi #{IMAGE}:#{tag}" do |ok,status|
end
else
sh "docker tag #{IMAGE}:#{tag} #{IMAGE}:latest"
end
end
end
end
task "start-this" do
status = get_status
if status != "no-container"
puts "unexpected image status: #{status}"
exit 1
end
opt = DOCKER_OPT.dup
if File.exist?("#{DIR}/Dockeropt")
opt << " "
opt << File.open("#{DIR}/Dockeropt"){|f|f.gets||""}.chomp
end
sh "docker run -d --name #{NAME} #{opt} #{IMAGE}:latest"
end
task "start" => ["start-this"] do
if File.exist?("#{DIR}/post-start.sh")
sh "bash -v #{DIR}/post-start.sh"
end
end
task "stop" do
status = get_status
if status == "paused"
sh "docker unpause #{NAME}"
status = get_status
end
if status == "running"
sh "docker stop #{NAME}"
status = get_status
end
if status == "exited"
sh "docker rm #{NAME}"
status = get_status
end
end
task "restart" => ["stop", "start"]
task "upgrade" => ["build", "restart"]
def get_status
# image exists?
cmd = "docker images #{IMAGE} | awk 'NR>1 && $2==\"latest\" {print $3}'"
result = %x{#{cmd}}
if result.length == 0
return "no-image"
end
cmd = "docker ps -a | awk -v name=#{NAME} 'NR>1 && $(NF)==name {print $1}'"
result = %x{#{cmd}}
if result.length == 0
return "no-container"
end
cmd = "docker ps -a -f status=paused | awk -v name=#{NAME} 'NR>1 && $(NF)==name {print $1}'"
result = %x{#{cmd}}
if result.length > 0
return "paused"
end
cmd = "docker ps -a -f status=exited | awk -v name=#{NAME} 'NR>1 && $(NF)==name {print $1}'"
result = %x{#{cmd}}
if result.length > 0
return "exited"
end
cmd = "docker ps -a -f status=running | awk -v name=#{NAME} 'NR>1 && $(NF)==name {print $1}'"
result = %x{#{cmd}}
if result.length > 0
return "running"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment