概述

这是一个专门用于管理Nginx静态网站Docker容器的自动化重建脚本。该脚本采用"每次强制重建"的策略,确保每次部署都在全新的环境中进行,从而避免潜在的配置残留问题。

系统要求

  1. 环境要求
  • 操作系统:支持Bash的Linux/Unix系统
  • Docker版本:需要安装并运行Docker服务
  • 权限要求:具有Docker操作权限和端口访问权限
  1. 依赖检查

    脚本会自动检查:

  • Docker服务运行状态
  • 所需镜像是否存在
  • 指定端口是否可用
  • 数据卷目录权限

使用方法

# 执行容器重建
./restart.sh

# 查看帮助信息
./restart.sh --help
./restart.sh -h

执行流程

  1. 运行环境检查

    1. Docker服务状态检查
    2. 镜像存在性检查
    3. 端口占用检查
  2. 清理现有容器

    1. 停止当前运行的同名容器
    2. 删除已存在的容器
  3. 创建新容器

    1. 配置数据卷挂载
    2. 设置端口映射
    3. 应用重启策略
  4. 部署确认

    1. 验证容器运行状态
    2. 显示容器详细信息

特性

  1. 强制重建机制

    1. 每次执行都会完全重建容器
    2. 确保环境的纯净性
    3. 避免配置污染
  2. 增强的错误处理

    1. 完整的前置条件检查
    2. 详细的错误提示
    3. 失败操作自动退出
  3. 改进的日志系统

    1. 时间戳记录
    2. 分级日志(INFO/WARN/ERROR)
    3. 彩色输出区分不同类型信息

      1. 绿色:成功信息
      2. 黄色:警告信息
      3. 红色:错误信息
  4. 状态反馈

    1. 实时操作状态显示
    2. 完整的容器信息输出
    3. 清晰的执行步骤提示

部署流程

构建static-html镜像:

  1. 先编译nginx docker容器
mkdir static-html && cd static-html

vi Dockerfile
  1. Dockerfile写入下面内容
FROM nginx:alpine
  1. 执行编译
docker build -t static-html:v1 .

# 查看编译的镜像内容
docker images | grep static-html
  1. 准备nginx配置
mkdir -p $PWD/nginx/conf.d
vi $PWD/nginx/conf.d/default.conf
  1. 设置配置,这里可以使用你自己的配置
server {
    listen 80;
    server_name localhost;

    root /usr/share/nginx/html;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }

    error_page 404 /404.html;
}
  1. 此时可以直接运行
docker run -d -p 90:80 \
--name static-html \
-v $PWD/data:/usr/share/nginx/html \
--restart unless-stopped \
static-html:v1

创建操作脚本:

  1. 但是也可以创建restart.sh等一些方便的脚本来处理
#!/bin/bash

# Colors for user-friendly output
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
RED="\033[0;31m"
RESET="\033[0m"

# Script information
SCRIPT_VERSION="1.0.0"
LAST_MODIFIED="2024-12-26"
AUTHOR="taliove"

# Configuration
CONTAINER_NAME="static-html"
IMAGE_NAME="static-html:v1"
HOST_PORT=90
CONTAINER_PORT=80
RESTART_POLICY="unless-stopped"

# Define volumes as an array
VOLUMES=(
    "$PWD/data:/usr/share/nginx/html"
    "$PWD/logs:/var/log/nginx"
    "$PWD/nginx/conf.d:/etc/nginx/conf.d"
)

# Function to log messages
log() {
    local level=$1
    local message=$2
    local color=$RESET
    
    case $level in
        "INFO") color=$GREEN ;;
        "WARN") color=$YELLOW ;;
        "ERROR") color=$RED ;;
    esac
    
    echo -e "${color}[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message${RESET}"
}

# Show help message if needed
if [[ $1 == "--help" || $1 == "-h" ]]; then
    echo -e "${YELLOW}Usage:${RESET} $0 [OPTIONS]"
    echo -e "\nThis script removes and recreates a Docker container with the following settings:"
    echo -e "  Container Name: ${CONTAINER_NAME}"
    echo -e "  Image Name: ${IMAGE_NAME}"
    echo -e "  Host Port: ${HOST_PORT}"
    echo -e "  Container Port: ${CONTAINER_PORT}"
    echo -e "\nVolumes:"
    for VOLUME in "${VOLUMES[@]}"; do
        echo -e "  - ${VOLUME}"
    done
    echo -e "\nScript Information:"
    echo -e "  Version: ${SCRIPT_VERSION}"
    echo -e "  Last Modified: ${LAST_MODIFIED}"
    echo -e "  Author: ${AUTHOR}"
    exit 0
fi

# Function to check if Docker is running
check_docker() {
    if ! docker info >/dev/null 2>&1; then
        log "ERROR" "Docker is not running or you don't have permission to access it"
        exit 1
    fi
}

# Function to stop and remove container if it exists
remove_container() {
    if docker ps -a --filter "name=${CONTAINER_NAME}" --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
        log "INFO" "Found existing container '${CONTAINER_NAME}'. Removing it..."
        if ! docker rm -f "${CONTAINER_NAME}" > /dev/null 2>&1; then
            log "ERROR" "Failed to remove container '${CONTAINER_NAME}'"
            exit 1
        fi
        log "INFO" "Successfully removed container '${CONTAINER_NAME}'"
    else
        log "INFO" "No existing container named '${CONTAINER_NAME}' found"
    fi
}

# Function to check if image exists
check_image() {
    if ! docker image inspect "${IMAGE_NAME}" >/dev/null 2>&1; then
        log "ERROR" "Image '${IMAGE_NAME}' not found"
        exit 1
    fi
}

# Function to check if port is available
check_port() {
    if lsof -Pi :${HOST_PORT} -sTCP:LISTEN -t >/dev/null 2>&1; then
        log "ERROR" "Port ${HOST_PORT} is already in use"
        exit 1
    fi
}

# Function to create and start container
create_container() {
    # Construct volume arguments
    log "INFO" "Preparing volume arguments..."
    local volume_args=""
    for VOLUME in "${VOLUMES[@]}"; do
        volume_args+=" -v $VOLUME"
    done

    # Create and start the container
    log "INFO" "Creating new container '${CONTAINER_NAME}'..."
    if eval "docker run -d \
        -p ${HOST_PORT}:${CONTAINER_PORT} \
        --name ${CONTAINER_NAME} \
        ${volume_args} \
        --restart ${RESTART_POLICY} \
        ${IMAGE_NAME}"; then
        log "INFO" "Successfully created and started container '${CONTAINER_NAME}'"
    else
        log "ERROR" "Failed to create and start container"
        exit 1
    fi
}

# Main execution
log "INFO" "Starting container deployment process..."

# Check prerequisites
check_docker
check_image
check_port

# Remove existing container
remove_container

# Create new container
create_container

# Verify container is running
if docker ps --filter "name=${CONTAINER_NAME}" --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
    log "INFO" "Container '${CONTAINER_NAME}' is now running"
    
    # Display container information
    echo -e "\n${GREEN}Container Details:${RESET}"
    docker ps --filter "name=${CONTAINER_NAME}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
else
    log "ERROR" "Container failed to start properly"
    exit 1
fi
  1. 创建stop.sh
#!/bin/bash

# Set container name
CONTAINER_NAME="static-html"

# Check if the container exists
if docker ps -a --filter "name=${CONTAINER_NAME}" --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
    echo "Stopping and removing the container: ${CONTAINER_NAME}"
    docker stop "${CONTAINER_NAME}" && docker rm "${CONTAINER_NAME}"
else
    echo "No container named ${CONTAINER_NAME} found."
fi
  1. 赋权
chmod +x restart.sh stop.sh

故障排除

  1. 常见问题

    1. Docker服务未运行

      1. 错误:Docker is not running or you don't have permission to access it
      2. 解决:启动Docker服务或检查权限
    2. 端口被占用

      1. 错误:Port 90 is already in use
      2. 解决:释放端口或修改配置
    3. 镜像不存在

      1. 错误:Image 'static-html:v1' not found
      2. 解决:构建或拉取所需镜像

常见命令使用

  1. 检查nginx配置是否正确
docker exec -it static-html nginx -t
  1. 重载nginx
docker exec -it static-html nginx -s reload

标签: Docker, Nginx

添加新评论