infrastructure-setup.md 16 KB

基础服务准备与配置指南

概述

本文档详细介绍了物联网基站管理系统所需的基础服务(PostgreSQL、InfluxDB、Redis、NATS、MQTT)的安装、配置和集成方法。特别针对已有Redis容器的情况提供了灵活的配置方案。

服务架构

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   PostgreSQL    │    │    InfluxDB     │    │      Redis      │
│   (元数据)      │    │   (时序数据)     │    │    (缓存)       │
│                 │    │                 │    │                 │
│ Port: 5432     │    │ Port: 8086     │    │ Port: 6379     │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 │
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│      NATS      │    │      MQTT      │    │   IoT应用       │
│   (消息队列)     │    │   (设备通信)     │    │                │
│                 │    │                 │    │                 │
│ Port: 4222     │    │ Port: 1883     │    │ Port: 8080     │
└─────────────────┘    └─────────────────┘    └─────────────────┘

服务配置选项

选项1:使用Docker Compose(推荐)

完整启动所有服务(包括Redis):

# 启动所有服务
docker-compose up -d

# 查看服务状态
docker-compose ps

# 查看服务日志
docker-compose logs -f

选项2:使用现有Redis + Docker Compose

如果您已有Redis容器,可以修改Docker Compose配置:

# 启动除Redis外的服务
docker-compose up -d postgres influxdb nats mqtt

# 或者使用自定义配置文件
docker-compose -f docker-compose-without-redis.yml up -d

选项3:混合部署(本地服务 + Docker)

结合本地已有服务和Docker容器:

# 仅启动Docker中的服务
docker-compose up -d postgres influxdb nats mqtt

# 使用本地Redis(确保已运行)
# 无需额外操作,应用会自动连接到本地Redis

各服务详细配置

1. PostgreSQL(元数据存储)

Docker部署

# docker-compose.yml 中的PostgreSQL配置
postgres:
  image: postgres:14
  environment:
    - POSTGRES_USER=postgres
    - POSTGRES_PASSWORD=postgres
    - POSTGRES_DB=iot_base_station
  ports:
    - "5432:5432"
  volumes:
    - postgres_data:/var/lib/postgresql/data
    - ./scripts/init-postgres.sql:/docker-entrypoint-initdb.d/init-postgres.sql

本地安装

# Ubuntu/Debian
sudo apt update
sudo apt install postgresql postgresql-contrib

# CentOS/RHEL
sudo yum install postgresql-server postgresql-contrib
sudo postgresql-setup initdb
sudo systemctl start postgresql
sudo systemctl enable postgresql

# macOS (使用Homebrew)
brew install postgresql
brew services start postgresql

配置数据库

# 创建数据库和用户
sudo -u postgres psql
CREATE USER iot_user WITH PASSWORD 'iot_password';
CREATE DATABASE iot_base_station OWNER iot_user;
GRANT ALL PRIVILEGES ON DATABASE iot_base_station TO iot_user;
\q

# 运行迁移
go run cmd/migrate/main.go up

连接测试

# 使用psql连接
psql -h localhost -U postgres -d iot_base_station

# 或使用Docker
docker-compose exec postgres psql -U postgres -d iot_base_station

2. InfluxDB(时序数据存储)

Docker部署

# docker-compose.yml 中的InfluxDB配置
influxdb:
  image: influxdb:2.0
  environment:
    - DOCKER_INFLUXDB_INIT_MODE=setup
    - DOCKER_INFLUXDB_INIT_USERNAME=admin
    - DOCKER_INFLUXDB_INIT_PASSWORD=adminpassword
    - DOCKER_INFLUXDB_INIT_ORG=iot-org
    - DOCKER_INFLUXDB_INIT_BUCKET=iot-data
    - DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=influxdb-token
  ports:
    - "8086:8086"
  volumes:
    - influxdb_data:/var/lib/influxdb2

本地安装

# 下载InfluxDB 2.0
wget https://dl.influxdata.com/influxdb/releases/influxdb2-2.0.7-linux-amd64.tar.gz
tar xvfz influxdb2-2.0.7-linux-amd64.tar.gz
sudo cp influxdb2-2.0.7-linux-amd64/influxd /usr/local/bin/

# 创建配置目录
sudo mkdir -p /etc/influxdb2
sudo chown $USER:$USER /etc/influxdb2

# 启动InfluxDB
influxd --config-path /etc/influxdb2

初始化配置

# 访问Web UI进行初始化
open http://localhost:8086

# 或使用CLI初始化
influx setup \
  --username admin \
  --password adminpassword \
  --org iot-org \
  --bucket iot-data \
  --retention 30d \
  --force

连接测试

# 检查健康状态
curl -s http://localhost:8086/health

# 使用CLI查询
influx query 'from(bucket:"iot-data") |> range(start:-1h)'

3. Redis(缓存)

使用现有Redis容器

如果您已有Redis容器,只需确保以下配置:

  1. 端口映射:确保Redis端口映射到主机

    # 检查现有Redis容器端口映射
    docker ps | grep redis
    # 如果没有端口映射,重新启动容器
    docker stop redis-container
    docker run -d --name redis-container -p 6379:6379 redis:6-alpine
    
  2. 网络连接:确保应用可以连接到Redis

    # 测试连接
    docker-compose exec app ping redis-container
    # 或使用主机网络
    docker run --network host redis-cli ping
    
  3. 配置文件更新:修改应用配置以使用现有Redis

    # config/config.dev.yaml
    redis:
     host: "localhost"  # 或 "host.docker.internal" 如果在Docker中
     port: "6379"
     password: ""  # 如果有密码,请填写
     db: 0
    

Docker部署(如果需要)

# docker-compose.yml 中的Redis配置
redis:
  image: redis:6-alpine
  ports:
    - "6379:6379"
  volumes:
    - redis_data:/data
  command: redis-server --appendonly yes

本地安装

# Ubuntu/Debian
sudo apt update
sudo apt install redis-server

# CentOS/RHEL
sudo yum install redis
sudo systemctl start redis
sudo systemctl enable redis

# macOS (使用Homebrew)
brew install redis
brew services start redis

配置优化

# 编辑Redis配置文件
sudo nano /etc/redis/redis.conf

# 推荐配置
maxmemory 256mb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000

# 重启Redis
sudo systemctl restart redis

连接测试

# 使用redis-cli
redis-cli ping

# 或使用Docker
docker-compose exec redis redis-cli ping

# 测试读写
redis-cli set test_key "test_value"
redis-cli get test_key

4. NATS(消息队列)

Docker部署

# docker-compose.yml 中的NATS配置
nats:
  image: nats:2-alpine
  ports:
    - "4222:4222"
    - "8222:8222"  # HTTP监控端口
  command: ["-js", "-m", "8222"]  # 启用JetStream和监控

本地安装

# 下载NATS Server
wget https://github.com/nats-io/nats-server/releases/download/v2.9.1/nats-server-v2.9.1-linux-amd64.tar.gz
tar xvfz nats-server-v2.9.1-linux-amd64.tar.gz
sudo cp nats-server-v2.9.1-linux-amd64/nats-server /usr/local/bin/

# 启动NATS
nats-server -js -m 8222

配置文件

# 创建NATS配置文件
mkdir -p ~/.config/nats
cat > ~/.config/nats/nats.conf << EOF
server_name: "nats-iot"
jetstream: {
  store_dir: "/tmp/nats-jetstream"
  max_memory_store: 1GB
  max_file_store: 10GB
}

http_port: 8222
EOF

# 使用配置文件启动
nats-server -c ~/.config/nats/nats.conf

连接测试

# 检查NATS状态
curl -s http://localhost:8222/varz | jq

# 使用nats-cli测试
nats sub "test.subject" &
nats pub "test.subject" "Hello, NATS!"

5. MQTT(设备通信)

Docker部署

# docker-compose.yml 中的MQTT配置
mqtt:
  image: eclipse-mosquitto:2
  ports:
    - "1883:1883"
    - "9001:9001"  # WebSocket端口
  volumes:
    - ./config/mosquitto.conf:/mosquitto/config/mosquitto.conf
    - mqtt_data:/mosquitto/data
    - mqtt_logs:/mosquitto/log

Mosquitto配置

# 创建Mosquitto配置文件
mkdir -p config
cat > config/mosquitto.conf << EOF
# 基本配置
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log
log_type error
log_type warning
log_type notice
log_type information

# 网络配置
listener 1883
protocol mqtt

# WebSocket支持
listener 9001
protocol websockets

# 认证(可选)
# allow_anonymous false
# password_file /mosquitto/config/passwd
EOF

本地安装

# Ubuntu/Debian
sudo apt update
sudo apt install mosquitto mosquitto-clients

# CentOS/RHEL
sudo yum install mosquitto
sudo systemctl start mosquitto
sudo systemctl enable mosquitto

# macOS (使用Homebrew)
brew install mosquitto
brew services start mosquitto

连接测试

# 订阅主题
mosquitto_sub -h localhost -t "iot/data/+/+"

# 发布消息
mosquitto_pub -h localhost -t "iot/data/test/temperature" -m '{"temperature": 25.5}'

# 或使用Docker
docker-compose exec mqtt mosquitto_sub -h localhost -t "iot/data/+/+"
docker-compose exec mqtt mosquitto_pub -h localhost -t "iot/data/test/temperature" -m '{"temperature": 25.5}'

服务集成配置

1. 应用配置文件

创建适合您环境的配置文件:

# 复制基础配置
cp config/config.yaml config/config.local.yaml

编辑 config/config.local.yaml

server:
  port: "8080"
  mode: "debug"

database:
  postgres:
    host: "localhost"  # 或 "host.docker.internal"
    port: "5432"
    user: "postgres"
    password: "postgres"
    dbname: "iot_base_station"
  
  influxdb:
    url: "http://localhost:8086"
    token: "influxdb-token"
    org: "iot-org"
    bucket: "iot-data"

redis:
  host: "localhost"  # 或 "host.docker.internal"
  port: "6379"
  password: ""  # 如果有密码,请填写
  db: 0

nats:
  url: "nats://localhost:4222"

mqtt:
  broker: "tcp://localhost:1883"
  client_id: "iot-gateway-dev"

2. 环境变量

创建 .env 文件:

# .env
CONFIG_PATH=config/config.local.yaml
GIN_MODE=debug

# 如果使用Docker中的服务
POSTGRES_HOST=postgres
INFLUXDB_URL=http://influxdb:8086
REDIS_HOST=redis
NATS_URL=nats://nats:4222
MQTT_BROKER=tcp://mqtt:1883

3. Docker Compose自定义配置

如果您已有Redis容器,可以创建自定义的Docker Compose文件:

# docker-compose-without-redis.yml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      - DB_HOST=postgres
      - DB_PORT=5432
      - DB_USER=postgres
      - DB_PASSWORD=postgres
      - DB_NAME=iot_base_station
      - INFLUXDB_URL=http://influxdb:8086
      - INFLUXDB_TOKEN=influxdb-token
      - INFLUXDB_ORG=iot-org
      - INFLUXDB_BUCKET=iot-data
      - REDIS_HOST=host.docker.internal  # 使用主机上的Redis
      - REDIS_PORT=6379
      - NATS_URL=nats://nats:4222
      - MQTT_BROKER=tcp://mqtt:1883
    depends_on:
      - postgres
      - influxdb
      - nats
      - mqtt
    volumes:
      - ./logs:/app/logs
      - ./uploads:/app/uploads
    networks:
      - iot-network
    extra_hosts:
      - "host.docker.internal:host-gateway"  # 允许访问主机服务

  postgres:
    image: postgres:14
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=iot_base_station
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - iot-network

  influxdb:
    image: influxdb:2.0
    environment:
      - DOCKER_INFLUXDB_INIT_MODE=setup
      - DOCKER_INFLUXDB_INIT_USERNAME=admin
      - DOCKER_INFLUXDB_INIT_PASSWORD=adminpassword
      - DOCKER_INFLUXDB_INIT_ORG=iot-org
      - DOCKER_INFLUXDB_INIT_BUCKET=iot-data
      - DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=influxdb-token
    ports:
      - "8086:8086"
    volumes:
      - influxdb_data:/var/lib/influxdb2
    networks:
      - iot-network

  nats:
    image: nats:2-alpine
    ports:
      - "4222:4222"
      - "8222:8222"
    command: ["-js", "-m", "8222"]
    networks:
      - iot-network

  mqtt:
    image: eclipse-mosquitto:2
    ports:
      - "1883:1883"
      - "9001:9001"
    volumes:
      - ./config/mosquitto.conf:/mosquitto/config/mosquitto.conf
      - mqtt_data:/mosquitto/data
      - mqtt_logs:/mosquitto/log
    networks:
      - iot-network

volumes:
  postgres_data:
  influxdb_data:
  mqtt_data:
  mqtt_logs:

networks:
  iot-network:
    driver: bridge

服务启动脚本

1. 完整启动脚本

#!/bin/bash
# scripts/start-infrastructure.sh

set -e

echo "=== 启动物联网基站基础服务 ==="

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "错误: Docker未运行,请先启动Docker"
    exit 1
fi

# 检查Redis是否已运行
if docker ps --format "table {{.Names}}" | grep -q "redis"; then
    echo "✓ 检测到Redis容器已运行"
    echo "启动除Redis外的服务..."
    docker-compose -f docker-compose-without-redis.yml up -d
else
    echo "Redis容器未运行,启动所有服务..."
    docker-compose up -d
fi

# 等待服务启动
echo "等待服务启动..."
sleep 10

# 检查服务状态
echo "检查服务状态..."
docker-compose ps

# 初始化数据库
echo "初始化数据库..."
docker-compose exec -T postgres psql -U postgres -c "CREATE DATABASE iot_base_station;" || echo "数据库可能已存在"

# 运行迁移
echo "运行数据库迁移..."
go run cmd/migrate/main.go up

echo "=== 基础服务启动完成 ==="
echo "PostgreSQL: localhost:5432"
echo "InfluxDB: http://localhost:8086"
echo "Redis: localhost:6379"
echo "NATS: localhost:4222"
echo "MQTT: localhost:1883"

2. 服务健康检查脚本

#!/bin/bash
# scripts/health-check.sh

echo "=== 服务健康检查 ==="

# 检查PostgreSQL
if docker-compose exec -T postgres pg_isready -U postgres > /dev/null 2>&1; then
    echo "✓ PostgreSQL: 健康"
else
    echo "✗ PostgreSQL: 不可用"
fi

# 检查InfluxDB
if curl -s http://localhost:8086/health > /dev/null 2>&1; then
    echo "✓ InfluxDB: 健康"
else
    echo "✗ InfluxDB: 不可用"
fi

# 检查Redis
if docker-compose exec -T redis redis-cli ping > /dev/null 2>&1; then
    echo "✓ Redis: 健康"
else
    echo "✗ Redis: 不可用"
fi

# 检查NATS
if curl -s http://localhost:8222/varz > /dev/null 2>&1; then
    echo "✓ NATS: 健康"
else
    echo "✗ NATS: 不可用"
fi

# 检查MQTT
if docker-compose exec -T mqtt mosquitto_pub -h localhost -t '$SYS/broker/version' -m 'test' > /dev/null 2>&1; then
    echo "✓ MQTT: 健康"
else
    echo "✗ MQTT: 不可用"
fi

echo "=== 健康检查完成 ==="

故障排除

1. 端口冲突

# 查找占用端口的进程
lsof -i :5432  # PostgreSQL
lsof -i :8086  # InfluxDB
lsof -i :6379  # Redis
lsof -i :4222  # NATS
lsof -i :1883  # MQTT

# 停止占用端口的进程
kill -9 <PID>

2. 网络连接问题

# 检查Docker网络
docker network ls
docker network inspect iot-base-station_iot-network

# 测试容器间连接
docker-compose exec app ping postgres
docker-compose exec app ping redis

3. 数据持久化问题

# 检查Docker卷
docker volume ls
docker volume inspect iot-base-station_postgres_data

# 备份数据
docker-compose exec postgres pg_dump -U postgres iot_base_station > backup.sql

4. 性能优化

# 监控资源使用
docker stats

# 调整容器资源限制
# 在docker-compose.yml中添加
services:
  postgres:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 1G

生产环境注意事项

  1. 安全性

    • 更改默认密码
    • 启用TLS/SSL
    • 配置防火墙规则
  2. 备份策略

    • 定期备份PostgreSQL数据库
    • 备份InfluxDB数据
    • 备份配置文件
  3. 监控

    • 设置服务健康检查
    • 配置告警通知
    • 监控资源使用情况
  4. 高可用性

    • 配置主从复制
    • 设置负载均衡
    • 实现故障转移

通过以上配置,您可以根据自己的环境需求灵活部署物联网基站管理系统的基础服务。