Last active
August 13, 2019 09:12
-
-
Save yukal/542435d17f1c678805e1bdb81847da9b to your computer and use it in GitHub Desktop.
The universal bash script to start Docker container or image
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
#!/usr/bin/bash | |
# This is a bash script for backend serving | |
# using the Docker | |
# | |
# Author: Yukal Alexander <[email protected]> | |
# License MIT | |
# Version: 3.0 | |
# Set variables | |
APP_NAME=${PWD##*/} | |
APP_IMAGE=$APP_NAME:backend | |
NODE_IMAGE=node:11-alpine | |
PORTS=5000:5000 | |
WORKDIR=/home/node | |
IMAGE_ID=$(docker image ls -q "${APP_NAME}") | |
# Dockerfile Contents | |
read -r -d '' DOCKERFILE << EOM | |
FROM $NODE_IMAGE | |
WORKDIR $WORKDIR | |
RUN apk update \ | |
&& apk upgrade \ | |
&& apk --no-cache add --virtual bash \ | |
&& apk --no-cache add --virtual mc \ | |
&& apk --no-cache add --virtual native-deps\ | |
&& apk --no-cache add --virtual g++ \ | |
&& apk --no-cache add --virtual gcc \ | |
&& apk --no-cache add --virtual libgcc \ | |
&& apk --no-cache add --virtual libstdc++ \ | |
&& apk --no-cache add --virtual linux-headers \ | |
&& apk --no-cache add --virtual make\ | |
&& apk --no-cache add --virtual python \ | |
&& npm i -g --unsafe-perm node-gyp \ | |
&& apk del native-deps | |
EOM | |
if [ -z "$IMAGE_ID" ]; then | |
echo "CREATE IMAGE FROM {$APP_IMAGE}"; | |
docker build - <<< "${DOCKERFILE}" --tag $APP_IMAGE | |
fi | |
# Get container ID and state of the Docker image | |
CONTAINER_ID=$(docker ps -q -a -f name="${APP_NAME}") | |
if [ -z "$CONTAINER_ID" ]; | |
then CONTAINER_STATE=false | |
else CONTAINER_STATE=$(docker inspect -f {{.State.Running}} $CONTAINER_ID) | |
fi | |
# Set arguments for Docker | |
if [ -z "$1" ]; | |
then ARG="bash"; | |
else ARG="$1"; | |
fi | |
if [ -z "$CONTAINER_ID" ]; then | |
# Container hasn't found. Run it from an image | |
docker run -it --rm --name $APP_NAME -p "${PORTS}" \ | |
-network default \ | |
-v "${PWD}":"${WORKDIR}" \ | |
-w "${WORKDIR}" $APP_IMAGE $ARG | |
else | |
# Container has found. Run it from the container | |
if [ "$CONTAINER_STATE" == "true" ]; then | |
docker exec -it $CONTAINER_ID $ARG | |
else | |
docker container start -ai $CONTAINER_ID | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment