Dockerのコンテナを操作するRakefile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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