Commit c9f98140 authored by duanjinfei's avatar duanjinfei

feat:edit docker file

parent 37809aef
.env
*.log
logs/
chainsql.log
*.sql
backup*.sql.gz
# ChainSQL 环境变量配置
# 复制此文件为 .env 并填入实际值
# 版本信息
VERSION=v1.0.0
BUILD_TIME=2024-01-23
# 区块链配置
CHAIN_RPC_URL=https://rpc.ankr.com/eth
CHAIN_FACTORY_ADDRESS=0x5FbDB2315678afecb367f032d93F642f64180aa3
CHAIN_CHAIN_ID=1
# 日志级别 (debug, info, warn, error)
LOG_LEVEL=info
# 数据库配置(通常不需要修改,除非自定义部署)
# DATABASE_DSN=postgres://chainsql:password123@postgres:5432/chainsql?sslmode=disable
# --- Build Stage ---
FROM golang:1.22-alpine AS builder
# 安装构建依赖 (git 等)
RUN apk add --no-cache git
WORKDIR /app
# 预先下载依赖,利用 Docker 缓存层
COPY go.mod go.sum ./
RUN go mod download
# 复制源代码
COPY . .
# 编译 (CGO_ENABLED=0 静态链接)
RUN CGO_ENABLED=0 GOOS=linux go build -o chainsql ./cmd/main.go
# --- Final Stage ---
FROM alpine:3.19
WORKDIR /app
# 安装必要的运行时库 (CA 证书用于 HTTPS 请求)
RUN apk add --no-cache ca-certificates tzdata
# 从 Build 阶段复制二进制文件
COPY --from=builder /app/chainsql .
# 复制配置文件 (注意:生产环境通常挂载 ConfigMap,这里作为默认值)
COPY configs/ ./configs/
# 暴露端口 (如果有 HTTP 服务的话)
# EXPOSE 8080
# 运行
CMD ["./chainsql"]
\ No newline at end of file
FROM golang:1.22-alpine AS builder
# 安装构建依赖
RUN apk add --no-cache git ca-certificates
WORKDIR /app
# 预先下载依赖,利用 Docker 缓存层
COPY go.mod go.sum ./
RUN go mod download
# 复制源代码
COPY . .
# 编译 (CGO_ENABLED=0 静态链接,添加版本信息)
ARG VERSION=dev
ARG BUILD_TIME
RUN CGO_ENABLED=0 GOOS=linux go build \
-ldflags="-w -s -X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME}" \
-o chainsql ./cmd/main.go
# --- Final Stage ---
FROM alpine:3.19
# 创建非 root 用户
RUN addgroup -g 1000 chainsql && \
adduser -D -u 1000 -G chainsql chainsql
WORKDIR /app
# 安装必要的运行时库
RUN apk add --no-cache ca-certificates tzdata && \
update-ca-certificates
# 从 Build 阶段复制二进制文件
COPY --from=builder /app/chainsql .
# 复制配置文件
COPY --chown=chainsql:chainsql configs/ ./configs/
# 创建日志目录
RUN mkdir -p /app/logs && chown -R chainsql:chainsql /app
# 切换到非 root 用户
USER chainsql
# 暴露 HTTP API 端口
EXPOSE 8080
# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1
# 运行
CMD ["./chainsql"]
\ No newline at end of file
# ChainSQL Makefile
# 项目变量
BINARY_NAME=chainsql
DOCKER_IMAGE=chainsql-service
VERSION=0.1.0
DOCKER_IMAGE=chainsql
VERSION?=$(shell git describe --tags --always 2>/dev/null || echo "dev")
BUILD_TIME=$(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
GIT_COMMIT=$(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
LDFLAGS=-ldflags "-w -s -X main.Version=$(VERSION) -X main.BuildTime=$(BUILD_TIME) -X main.GitCommit=$(GIT_COMMIT)"
# Go 相关变量
GOBASE=$(shell pwd)
GOBIN=$(GOBASE)/bin
GOFILES=$(wildcard *.go)
# 颜色输出
GREEN=\033[0;32m
YELLOW=\033[1;33m
NC=\033[0m # No Color
.PHONY: all build run test clean help
.PHONY: docker-build docker-deploy docker-up docker-down docker-logs docker-clean
.PHONY: db-reset db-clean hardhat-deploy hardhat-test
.PHONY: lint fmt vet tidy deps
# 默认目标
all: build
# 编译 Go 二进制文件
build:
@echo "Building binary..."
@go build -o bin/$(BINARY_NAME) ./cmd/main.go
## Build Commands
build: ## 编译 Go 二进制文件
@echo "$(GREEN)Building $(BINARY_NAME) $(VERSION)...$(NC)"
@mkdir -p $(GOBIN)
@go build $(LDFLAGS) -o $(GOBIN)/$(BINARY_NAME) ./cmd/main.go
@echo "$(GREEN)✓ Build complete: $(GOBIN)/$(BINARY_NAME)$(NC)"
# 运行服务 (本地开发)
run: build
@echo "Running service..."
@./bin/$(BINARY_NAME)
build-linux: ## 编译 Linux 版本
@echo "$(GREEN)Building for Linux...$(NC)"
@mkdir -p $(GOBIN)
@GOOS=linux GOARCH=amd64 go build $(LDFLAGS) -o $(GOBIN)/$(BINARY_NAME)-linux ./cmd/main.go
# 整理依赖
tidy:
@go mod tidy
run: build ## 编译并运行服务
@echo "$(GREEN)Running $(BINARY_NAME)...$(NC)"
@$(GOBIN)/$(BINARY_NAME)
# 清理构建产物
clean:
@echo "Cleaning..."
@rm -rf bin/
## Docker Commands
docker-build: ## 构建 Docker 镜像
@./scripts/docker-build.sh
# Docker 构建
docker-build:
@echo "Building Docker image..."
@docker build -t $(DOCKER_IMAGE):$(VERSION) .
@docker tag $(DOCKER_IMAGE):$(VERSION) $(DOCKER_IMAGE):latest
docker-deploy: ## 部署 Docker 服务(完整流程)
@./scripts/docker-deploy.sh
# Docker Compose 启动 (需先安装 docker-compose)
docker-up:
@echo "Starting services with Docker Compose..."
docker-up: ## 启动 Docker Compose 服务
@echo "$(GREEN)Starting Docker services...$(NC)"
@docker-compose up -d
@echo "$(GREEN)✓ Services started$(NC)"
docker-down:
@echo "Stopping services..."
docker-down: ## 停止 Docker Compose 服务
@echo "$(YELLOW)Stopping Docker services...$(NC)"
@docker-compose down
@echo "$(GREEN)✓ Services stopped$(NC)"
docker-restart: ## 重启 ChainSQL 服务
@echo "$(YELLOW)Restarting ChainSQL...$(NC)"
@docker-compose restart chainsql
docker-logs: ## 查看 ChainSQL 日志
@docker-compose logs -f --tail=100 chainsql
docker-logs-db: ## 查看数据库日志
@docker-compose logs -f --tail=100 postgres
docker-logs-all: ## 查看所有服务日志
@docker-compose logs -f --tail=100
docker-ps: ## 查看服务状态
@docker-compose ps
docker-clean: ## 清理 Docker 资源(包括 volumes)
@echo "$(YELLOW)Cleaning Docker resources...$(NC)"
@docker-compose down -v
@docker system prune -f
@echo "$(GREEN)✓ Docker cleaned$(NC)"
docker-shell: ## 进入 ChainSQL 容器
@docker-compose exec chainsql sh
docker-db-shell: ## 进入数据库容器
@docker-compose exec postgres psql -U chainsql
## Database Commands
db-reset: ## 重置数据库游标
@echo "$(YELLOW)Resetting database cursors...$(NC)"
@sh scripts/reset-db.sh
db-clean: ## 清空所有 ChainSQL schemas
@echo "$(YELLOW)Cleaning ChainSQL schemas...$(NC)"
@sh scripts/clean-schemas.sh
db-backup: ## 备份数据库
@echo "$(GREEN)Backing up database...$(NC)"
@docker-compose exec -T postgres pg_dump -U chainsql chainsql | gzip > backup_$(shell date +%Y%m%d_%H%M%S).sql.gz
@echo "$(GREEN)✓ Backup created$(NC)"
## Hardhat Commands
hardhat-node: ## 启动 Hardhat 本地节点
@echo "$(GREEN)Starting Hardhat node...$(NC)"
@cd hardhat && npx hardhat node
hardhat-deploy: ## 部署智能合约到 Hardhat
@echo "$(GREEN)Deploying contracts...$(NC)"
@cd hardhat && npx hardhat run scripts/deploy.js --network localhost
hardhat-test: ## 运行 Hardhat 集成测试
@echo "$(GREEN)Running integration tests...$(NC)"
@cd hardhat && npx hardhat run scripts/integration-test.js --network localhost
hardhat-compile: ## 编译智能合约
@echo "$(GREEN)Compiling contracts...$(NC)"
@cd hardhat && npx hardhat compile
hardhat-clean: ## 清理 Hardhat 编译产物
@cd hardhat && npx hardhat clean
## Development Commands
test: ## 运行 Go 测试
@echo "$(GREEN)Running tests...$(NC)"
@go test -v -race -coverprofile=coverage.out ./...
@go tool cover -html=coverage.out -o coverage.html
@echo "$(GREEN)✓ Coverage report: coverage.html$(NC)"
lint: ## 运行 linter
@echo "$(GREEN)Running linter...$(NC)"
@golangci-lint run ./...
fmt: ## 格式化代码
@echo "$(GREEN)Formatting code...$(NC)"
@go fmt ./...
@goimports -w .
vet: ## 运行 go vet
@go vet ./...
tidy: ## 整理依赖
@echo "$(GREEN)Tidying dependencies...$(NC)"
@go mod tidy
@echo "$(GREEN)✓ Dependencies tidied$(NC)"
deps: ## 下载依赖
@echo "$(GREEN)Downloading dependencies...$(NC)"
@go mod download
## Cleanup Commands
clean: ## 清理构建产物
@echo "$(YELLOW)Cleaning build artifacts...$(NC)"
@rm -rf $(GOBIN)
@rm -rf coverage.out coverage.html
@rm -rf logs/*.log
@echo "$(GREEN)✓ Cleaned$(NC)"
clean-all: clean docker-clean ## 清理所有(包括 Docker)
@echo "$(GREEN)✓ All cleaned$(NC)"
## Utility Commands
version: ## 显示版本信息
@echo "Version: $(VERSION)"
@echo "Build Time: $(BUILD_TIME)"
@echo "Git Commit: $(GIT_COMMIT)"
health: ## 检查服务健康状态
@curl -sf http://localhost:8080/health || echo "Service not healthy"
metrics: ## 查看 Prometheus 指标
@curl -s http://localhost:8080/metrics
## Quick Start Commands
quickstart: ## 快速启动(Hardhat + ChainSQL)
@echo "$(GREEN)🚀 Quick Start$(NC)"
@echo "$(YELLOW)Step 1: Starting Hardhat node...$(NC)"
@cd hardhat && npx hardhat node &
@sleep 3
@echo "$(YELLOW)Step 2: Deploying contracts...$(NC)"
@$(MAKE) hardhat-deploy
@echo "$(YELLOW)Step 3: Resetting database...$(NC)"
@$(MAKE) db-reset
@echo "$(YELLOW)Step 4: Starting ChainSQL...$(NC)"
@$(MAKE) run
dev: ## 开发模式(监听文件变化)
@which air > /dev/null || go install github.com/cosmtrek/air@latest
@air
# 帮助信息
help:
@echo "Available commands:"
@echo " make build - Build the binary"
@echo " make run - Build and run locally"
@echo " make tidy - Run go mod tidy"
@echo " make clean - Remove binary"
@echo " make docker-build - Build Docker image"
@echo " make docker-up - Start services (DB + App)"
@echo " make docker-down - Stop services"
\ No newline at end of file
## Help
help: ## 显示帮助信息
@echo "$(GREEN)ChainSQL Makefile Commands:$(NC)"
@echo ""
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf " $(YELLOW)%-20s$(NC) %s\n", $$1, $$2}'
@echo ""
@echo "$(GREEN)Examples:$(NC)"
@echo " make build # 编译项目"
@echo " make docker-deploy # 完整 Docker 部署"
@echo " make hardhat-test # 运行集成测试"
@echo " make db-clean # 清空数据库"
@echo ""
\ No newline at end of file
......@@ -9,35 +9,90 @@ services:
POSTGRES_USER: chainsql
POSTGRES_PASSWORD: password123
POSTGRES_DB: chainsql
# 性能优化
POSTGRES_SHARED_BUFFERS: 256MB
POSTGRES_MAX_CONNECTIONS: 100
ports:
- "5432:5432"
volumes:
- pg_data:/var/lib/postgresql/data
# 可选:挂载初始化脚本
# - ./scripts/init-db.sql:/docker-entrypoint-initdb.d/init.sql
networks:
- chainsql-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U chainsql"]
test: [ "CMD-SHELL", "pg_isready -U chainsql" ]
interval: 5s
timeout: 5s
retries: 5
restart: unless-stopped
# 资源限制(可选)
deploy:
resources:
limits:
memory: 512M
reservations:
memory: 256M
# ChainSQL 服务
chainsql:
build: .
build:
context: .
dockerfile: Dockerfile
args:
VERSION: ${VERSION:-dev}
BUILD_TIME: ${BUILD_TIME:-unknown}
image: chainsql:${VERSION:-latest}
container_name: chainsql-app
depends_on:
postgres:
condition: service_healthy
environment:
# 覆盖 config.yaml 中的配置
CHAIN_RPC_URL: "https://rpc.ankr.com/eth" # 替换为你的 RPC
CHAIN_FACTORY_ADDRESS: "0x..." # 替换为 Factory 地址
CHAIN_RPC_URL: ${CHAIN_RPC_URL:-https://rpc.ankr.com/eth}
CHAIN_FACTORY_ADDRESS: ${CHAIN_FACTORY_ADDRESS:-0x...}
CHAIN_CHAIN_ID: ${CHAIN_CHAIN_ID:-1}
# 使用 Docker 网络中的 DB 地址
DATABASE_DSN: "postgres://chainsql:password123@postgres:5432/chainsql?sslmode=disable"
# 日志配置
LOG_LEVEL: ${LOG_LEVEL:-info}
ports:
- "8080:8080" # HTTP API
volumes:
# 挂载本地配置 (可选,方便开发调试)
- ./configs/config.yaml:/app/configs/config.yaml
- ./configs/config.yaml:/app/configs/config.yaml:ro
# 挂载 ABI 文件
- ./configs/abi.json:/app/configs/abi.json
- ./configs/abi.json:/app/configs/abi.json:ro
# 挂载日志目录
- ./logs:/app/logs
networks:
- chainsql-network
restart: unless-stopped
# 资源限制(可选)
deploy:
resources:
limits:
memory: 512M
reservations:
memory: 256M
# 健康检查
healthcheck:
test: [ "CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/health" ]
interval: 30s
timeout: 3s
start_period: 10s
retries: 3
# 日志配置
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
networks:
chainsql-network:
driver: bridge
volumes:
pg_data:
\ No newline at end of file
pg_data:
driver: local
File mode changed from 100644 to 100755
#!/bin/bash
# scripts/docker-build.sh
# Docker 镜像构建脚本
set -e
# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${GREEN}🐳 Building ChainSQL Docker Image${NC}"
# 获取版本信息
VERSION=${VERSION:-$(git describe --tags --always 2>/dev/null || echo "dev")}
BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
echo -e "${YELLOW}Version: ${VERSION}${NC}"
echo -e "${YELLOW}Build Time: ${BUILD_TIME}${NC}"
echo -e "${YELLOW}Git Commit: ${GIT_COMMIT}${NC}"
# 构建镜像
docker build \
--build-arg VERSION="${VERSION}" \
--build-arg BUILD_TIME="${BUILD_TIME}" \
--tag "chainsql:${VERSION}" \
--tag "chainsql:latest" \
.
echo -e "${GREEN}✅ Build completed successfully!${NC}"
echo -e "${YELLOW}Image tags:${NC}"
echo -e " - chainsql:${VERSION}"
echo -e " - chainsql:latest"
# 显示镜像信息
echo -e "\n${YELLOW}Image details:${NC}"
docker images chainsql --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}"
#!/bin/bash
# scripts/docker-deploy.sh
# Docker 部署脚本
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo -e "${GREEN}🚀 Deploying ChainSQL with Docker Compose${NC}"
# 检查 .env 文件
if [ ! -f .env ]; then
echo -e "${YELLOW}⚠️ .env file not found, creating from .env.example${NC}"
cp .env.example .env
echo -e "${RED}❗ Please edit .env file with your configuration before deploying!${NC}"
exit 1
fi
# 检查必要的环境变量
source .env
if [ "$CHAIN_FACTORY_ADDRESS" = "0x..." ]; then
echo -e "${RED}❌ Please set CHAIN_FACTORY_ADDRESS in .env file${NC}"
exit 1
fi
# 创建日志目录
mkdir -p logs
# 停止旧服务(如果存在)
echo -e "${YELLOW}Stopping existing services...${NC}"
docker-compose down 2>/dev/null || true
# 构建镜像
echo -e "${YELLOW}Building images...${NC}"
docker-compose build
# 启动服务
echo -e "${YELLOW}Starting services...${NC}"
docker-compose up -d
# 等待服务启动
echo -e "${YELLOW}Waiting for services to be healthy...${NC}"
sleep 5
# 检查服务状态
echo -e "\n${GREEN}Service Status:${NC}"
docker-compose ps
# 检查健康状态
echo -e "\n${YELLOW}Checking health status...${NC}"
for i in {1..30}; do
if curl -sf http://localhost:8080/health > /dev/null 2>&1; then
echo -e "${GREEN}✅ ChainSQL is healthy!${NC}"
break
fi
echo -n "."
sleep 1
done
echo -e "\n${GREEN}🎉 Deployment completed!${NC}"
echo -e "${YELLOW}Useful commands:${NC}"
echo -e " View logs: docker-compose logs -f chainsql"
echo -e " Stop: docker-compose down"
echo -e " Restart: docker-compose restart chainsql"
echo -e " Health check: curl http://localhost:8080/health"
#!/bin/bash
# scripts/docker-logs.sh
# 查看 Docker 日志的便捷脚本
SERVICE=${1:-chainsql}
LINES=${2:-100}
case "$SERVICE" in
chainsql|app)
docker-compose logs -f --tail=$LINES chainsql
;;
postgres|db)
docker-compose logs -f --tail=$LINES postgres
;;
all)
docker-compose logs -f --tail=$LINES
;;
*)
echo "Usage: $0 [chainsql|postgres|all] [lines]"
echo "Examples:"
echo " $0 chainsql 50 # Show last 50 lines of chainsql logs"
echo " $0 postgres # Show last 100 lines of postgres logs"
echo " $0 all # Show logs from all services"
exit 1
;;
esac
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment