Automating Dockerized App Deployment with a Bash Script

Published: (December 13, 2025 at 01:06 AM EST)
6 min read
Source: Dev.to

Source: Dev.to

DevOps is all about automation, reliability, and efficiency. In Stage 1 of my DevOps internship, I built a robust Bash script to automate the deployment of a Dockerized application to a remote Linux server.

Whether you’re a developer, system administrator, or DevOps enthusiast, this guide walks you step‑by‑step through creating a production‑ready deployment script that handles everything from cloning a repository to configuring Nginx as a reverse proxy.

Why automate deployments?

  • Consistency – Deployments are identical every time.
  • Speed – Reduces human intervention and saves time.
  • Reliability – Detects errors early and logs them for troubleshooting.

By the end of this guide, you’ll have a single Bash script (deploy.sh) capable of fully deploying your Dockerized app to a remote server.

Step 1: Collect Parameters from User Input

  • Git repository URL
  • Personal Access Token (PAT)
  • Branch name (defaults to main)
  • SSH credentials (username, server IP, key path)
  • Application port

We also validate the inputs to prevent script failure later.

# Git Repository URL
while [[ -z "${GIT_REPO_URL:-}" ]]; do
    read -rp "Enter the git repository URL: " GIT_REPO_URL
    [[ -z "$GIT_REPO_URL" ]] && log_error "Repository URL cannot be empty."
done

# Personal Access Token (PAT) - hidden input
while [[ -z "${GIT_PAT:-}" ]]; do
  read -rsp "Enter your Git Personal Access Token (PAT): " GIT_PAT
  echo ""
  [[ -z "$GIT_PAT" ]] && log_error "Personal Access Token cannot be empty."
done

# Branch name (default = main)
read -rp "Enter branch name [default: main]: " GIT_BRANCH
GIT_BRANCH=${GIT_BRANCH:-main}

# SSH username
while [[ -z "${SSH_USER:-}" ]]; do
    read -rp "Enter remote server SSH username: " SSH_USER
    [[ -z "$SSH_USER" ]] && log_error "SSH username cannot be empty."
done

# Server IP address
while [[ -z "${SERVER_IP:-}" ]]; do
    read -rp "Enter remote server IP address: " SERVER_IP
    if [[ ! "$SERVER_IP" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
        log_error "Invalid IP format. Please enter a valid IPV4 address."
        SERVER_IP=""
    fi
done

# SSH key path
while [[ -z "${SSH_KEY_PATH:-}" ]]; do
    read -rp "Enter path to SSH private key: " SSH_KEY_PATH
    if [[ ! -f "$SSH_KEY_PATH" ]]; then
        log_error "SSH key file not found at $SSH_KEY_PATH"
        SSH_KEY_PATH=""
    fi
done

# Application port (internal container port)
while [[ -z "${APP_PORT:-}" ]]; do
    read -rp "Enter internal application (container) port (e.g., 8080): " APP_PORT
    if ! [[ "$APP_PORT" =~ ^[0-9]+$ ]]; then
        log_error "Invalid port. Please enter a numeric value."
        APP_PORT=""
    fi
done

Tip: Always validate user input using conditionals to ensure URLs are valid and files exist.

Step 2: Clone or Pull the Repository

REPO_NAME=$(basename -s .git "$GIT_REPO_URL")
WORK_DIR="$HOME/deployment/$REPO_NAME"

# Create deployment directory if not exists
mkdir -p "$(dirname "$WORK_DIR")"

# Authenticated URL (PAT safely embedded)
GIT_USERNAME=$(echo "$GIT_REPO_URL" | awk -F[/:] '{print $(NF-1)}')
AUTH_REPO_URL=$(echo "$GIT_REPO_URL" | sed "s#https://#https://$GIT_USERNAME:$GIT_PAT@#")

if [[ -d "$WORK_DIR/.git" ]]; then
    log_info "Repository already exists. Pulling latest changes..."
    cd "$WORK_DIR"
    git reset --hard
    git clean -fd
    git fetch origin "$GIT_BRANCH"
    git checkout "$GIT_BRANCH"
    git pull origin "$GIT_BRANCH" || {
        log_error "Failed to pull latest changes from $GIT_BRANCH"
        exit $EXIT_UNKNOWN
    }
else
    log_info "Cloning repository into $WORK_DIR..."
    git clone --branch "$GIT_BRANCH" "$AUTH_REPO_URL" "$WORK_DIR" || {
        log_error "Failed to clone repository. Please check your URL or PAT"
        exit $EXIT_UNKNOWN
    }
    cd "$WORK_DIR"
fi

log_success "Repository is ready at: $WORK_DIR"

This step ensures your local project folder is always up‑to‑date with the remote repo.

Step 3: Verify Docker Configuration Files

# Check for Docker configuration files
if [[ -f "Dockerfile" ]]; then
    log_success "Found Dockerfile – ready for Docker build."
elif [[ -f "compose.yaml" || -f "compose.yml" || -f "docker-compose.yaml" || -f "docker-compose.yml" ]]; then
    log_success "Found docker-compose.yml – ready for multi‑service deployment."
else
    log_error "No Dockerfile or docker-compose.yml found. Cannot continue deployment."
    exit $EXIT_UNKNOWN
fi

Step 4: Test SSH Connectivity

# Validate SSH key exists
if [ ! -f "$SSH_KEY_PATH" ]; then
    log_error "SSH key not found at: $SSH_KEY_PATH"
    exit $EXIT_SSH_FAIL
fi

# Test SSH connection (non‑interactive)
ssh -i "$SSH_KEY_PATH" -o StrictHostKeyChecking=no -o BatchMode=yes \
    "$SSH_USER@$SERVER_IP" "echo 'SSH connection successful!'" >/dev/null 2>&1

if [ $? -ne 0 ]; then
    log_error "Unable to connect to remote server via SSH. Verify credentials, key permissions, and IP address."
    exit $EXIT_SSH_FAIL
else
    log_success "SSH connection verified successfully."
fi

Step 5: Prepare the Remote Environment

The script updates packages, installs Docker, Docker Compose, and Nginx, adds the SSH user to the Docker group, and ensures services are enabled and started.

ssh -i "$SSH_KEY_PATH" -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" bash /dev/null; then
    echo "Docker not found. Installing Docker..."
    curl -fsSL https://get.docker.com | sudo bash
else
    echo "Docker already installed."
fi

# Install Docker Compose if not present
if ! command -v docker-compose &>/dev/null; then
    echo "Installing Docker Compose..."
    sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" \
        -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose
else
    echo "Docker Compose already installed."
fi

# Install Nginx if not present
if ! command -v nginx &>/dev/null; then
    echo "Installing nginx..."
    sudo apt-get install -y nginx
else
    echo "nginx already installed."
fi

# Add SSH user to docker group
if ! groups $SSH_USER | grep -q docker; then
    echo "Adding user '$SSH_USER' to docker group..."
    sudo usermod -aG docker $SSH_USER
    echo "You may need to log out and back in for this to take effect."
else
    echo "User '$SSH_USER' already in docker group."
fi

# Enable and start services
sudo systemctl enable docker
sudo systemctl start docker
sudo systemctl enable nginx
sudo systemctl start nginx

# Confirm installation versions
docker --version
docker-compose --version
nginx -v

echo "Remote environment setup complete."
EOF

Best practice: Always confirm installation versions and service status after provisioning.

Step 6: Deploy the Dockerized Application

# Sync source code to remote server (excluding unnecessary files)
rsync -avz -e "ssh -i $SSH_KEY_PATH -o StrictHostKeyChecking=no" \
    --exclude '.git' --exclude 'node_modules' --exclude '.env' \
    "$WORK_DIR/" "$SSH_USER@$SERVER_IP:$REMOTE_APP_DIR" >/dev/null 2>&1

# Run deployment commands on the remote host
ssh -i "$SSH_KEY_PATH" -o StrictHostKeyChecking=no "$SSH_USER@$SERVER_IP" bash <<'EOF'
set -e

cd $REMOTE_APP_DIR

# Detect Docker configuration
if [[ -f "docker-compose.yml" ]]; then
    echo "docker-compose.yml found. Starting with Docker Compose..."
    sudo docker-compose pull
    sudo docker-compose build
    sudo docker-compose up -d
elif [[ -f "Dockerfile" ]]; then
    echo "Dockerfile found. Building and running manually..."
    APP_NAME=$(basename $(pwd))
    sudo docker build -t $APP_NAME .
    sudo docker run -d -p $APP_PORT:$APP_PORT --name $APP_NAME $APP_NAME
else
    echo "No Dockerfile or docker-compose.yml found in $REMOTE_APP_DIR"
    exit 1
fi
EOF

At this point the application should be running on the remote server, accessible through the configured Nginx reverse proxy.

Back to Blog

Related posts

Read more »