Skip to content

Instantly share code, notes, and snippets.

@wesleyit
Created June 8, 2015 21:03
Show Gist options
  • Save wesleyit/65a3356d0ba6d7362d66 to your computer and use it in GitHub Desktop.
Save wesleyit/65a3356d0ba6d7362d66 to your computer and use it in GitHub Desktop.
This script will ensure a container is deleted before start a new instance. It will map a folder of the host SO to a folder inside the container. In this sample I am using apache, but you can replace by any other application you need.
#!/bin/bash
## Define the container name to be used on all places along this script.
# If it is not na oficial image, set the builder too. Do not forget to add
# a slash at the end, like in "BUILDER=wesleyit/myimage"
BUILDER=''
CONTAINER='apache'
VERSION='latest'
## Set the ports used by the service
HOST_PORT=80
CONTAINER_PORT=80
## This is the persistence directory
STORE_DIR="/var/lib/docker/storage/$CONTAINER"
CONTAINER_DATA_DIR='/var/www/html'
## Verify if the container exists
function is_created() {
docker ps -a | grep -q "$1"
return "$?"
}
## Verify if there is an instance of this container executing at this moment
function is_running() {
docker ps | grep -q "$1"
return "$?"
}
## We need to guarantee the directory exists and is writable
mkdir -p $STORE_DIR && chmod 777 $STORE_DIR
if is_created $CONTAINER
then
if is_running $CONTAINER
then
echo -n "Killing container "
docker kill $CONTAINER
fi
echo -n "Deleting container "
docker rm $CONTAINER
sleep 5
fi
echo -n "Starting container $CONTAINER "
docker run -d \
--name "$CONTAINER" \
-p "$HOST_PORT":"$CONTAINER_PORT" \
-v "$STORE_DIR":"$CONTAINER_DATA_DIR" \
"$BUILDER""$CONTAINER":"$VERSION"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment