110 lines
2.7 KiB
Bash
110 lines
2.7 KiB
Bash
#!/bin/bash
|
|
|
|
echo "🚀 部署 Traefik + Consul 集群"
|
|
|
|
# 创建必要的目录
|
|
mkdir -p {certs,web-content,api,logs}
|
|
|
|
# 创建示例网页
|
|
cat > web-content/index.html << 'EOF'
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Traefik + Consul Demo</title>
|
|
</head>
|
|
<body>
|
|
<h1>🎉 Traefik + Consul 集群运行成功!</h1>
|
|
<p>当前时间: <span id="time"></span></p>
|
|
<script>
|
|
document.getElementById('time').textContent = new Date().toLocaleString();
|
|
</script>
|
|
</body>
|
|
</html>
|
|
EOF
|
|
|
|
# 创建示例 API
|
|
cat > api/server.js << 'EOF'
|
|
const express = require('express');
|
|
const consul = require('consul')();
|
|
const app = express();
|
|
const port = 3000;
|
|
|
|
app.use(express.json());
|
|
|
|
// 健康检查
|
|
app.get('/health', (req, res) => {
|
|
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
|
|
});
|
|
|
|
// API 路由
|
|
app.get('/api/config', async (req, res) => {
|
|
try {
|
|
const result = await consul.kv.get('config/api/message');
|
|
res.json({
|
|
message: result ? result.Value : 'Hello from API!',
|
|
source: 'consul'
|
|
});
|
|
} catch (error) {
|
|
res.json({
|
|
message: 'Hello from API!',
|
|
source: 'default'
|
|
});
|
|
}
|
|
});
|
|
|
|
app.post('/api/config', async (req, res) => {
|
|
try {
|
|
await consul.kv.set('config/api/message', req.body.message);
|
|
res.json({ success: true });
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
app.listen(port, () => {
|
|
console.log(`API server running on port ${port}`);
|
|
});
|
|
EOF
|
|
|
|
# 创建 API package.json
|
|
cat > api/package.json << 'EOF'
|
|
{
|
|
"name": "demo-api",
|
|
"version": "1.0.0",
|
|
"dependencies": {
|
|
"express": "^4.18.0",
|
|
"consul": "^0.40.0"
|
|
}
|
|
}
|
|
EOF
|
|
|
|
# 设置 hosts 文件(用于本地测试)
|
|
echo "📝 请添加以下内容到 /etc/hosts 文件:"
|
|
echo "127.0.0.1 traefik.local"
|
|
echo "127.0.0.1 consul.local"
|
|
echo "127.0.0.1 app.local"
|
|
echo "127.0.0.1 api.local"
|
|
|
|
# 启动服务
|
|
echo "🚀 启动 Traefik + Consul 集群..."
|
|
docker-compose -f traefik-consul-setup.yml up -d
|
|
|
|
# 等待服务启动
|
|
echo "⏳ 等待服务启动..."
|
|
sleep 10
|
|
|
|
# 检查服务状态
|
|
echo "📊 检查服务状态..."
|
|
docker-compose -f traefik-consul-setup.yml ps
|
|
|
|
# 显示访问地址
|
|
echo ""
|
|
echo "🎉 部署完成!访问地址:"
|
|
echo " Traefik Dashboard: http://traefik.local:8080"
|
|
echo " Consul UI: http://consul.local:8500"
|
|
echo " Web App: http://app.local"
|
|
echo " API: http://api.local/api/config"
|
|
echo ""
|
|
echo "📝 测试命令:"
|
|
echo " curl http://api.local/api/config"
|
|
echo " curl -X POST http://api.local/api/config -H 'Content-Type: application/json' -d '{\"message\":\"Hello Consul!\"}'" |