Created
August 20, 2017 10:10
-
-
Save mads-hartmann/415cba506a538f35a992598c9221432d to your computer and use it in GitHub Desktop.
A small script for deploying a Docker service to a docker-machine. Suitable to prototypes and small hobby projects.
This file contains hidden or 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
#!/bin/bash | |
# | |
# usage: prototype-deploy <machine-name> <image-name> <container-name> | |
# | |
set -euo pipefail | |
# | |
# Functions | |
# | |
# Convenience function for logging text to stdout in pretty colors. | |
function log { | |
local message="$@" | |
local green="\\033[1;32m" | |
local reset="\\033[0m" | |
if [[ $TERM == "dumb" ]] | |
then | |
echo "${message}" | |
else | |
echo -e "${green}${message}${reset}" | |
fi | |
} | |
# Check if a container with a given name already exists | |
function container_exists { | |
local container_name=$1 | |
if [[ -z "$(docker ps -q -f name=${container_name})" ]] | |
then false | |
else true | |
fi | |
} | |
# Get the image tag version based on the git SHA | |
function version { | |
git rev-parse HEAD | cut -c1-8 | |
} | |
# Build the Docker image and deploy it to a given Docker machine and | |
# give the container a specific name. | |
# Remove any containers that already exist with the given name. | |
function deploy { | |
local machine_name=$1 | |
local image_name=$2 | |
local container_name=$3 | |
log "Connection to machine" | |
eval $(docker-machine env ${machine_name}) | |
log "Building image" | |
docker build --tag ${image_name}:$(version) . | |
if container_exists ${container_name} | |
then | |
log "Deleting exiting container" | |
docker rm -f ${container_name} | |
fi | |
log "Starting containter" | |
docker run \ | |
--detach \ | |
--publish 80:80 \ | |
--name ${container_name} \ | |
${image_name}:$(version) | |
log "Now running on http://$(docker-machine ip ${machine_name})" | |
} | |
# | |
# Main | |
# | |
machine_name=$1 | |
image_name=$2 | |
container_name=$3 | |
deploy ${machine_name} ${image_name} ${container_name} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment