Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
82 lines (73 loc) · 2.21 KB
/
Copy pathapp.js
File metadata and controls
82 lines (73 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
// MongoDB 连接
mongoose.connect(process.env.MONGO_URI || 'mongodb://localhost:27017/devops_db', {
serverSelectionTimeoutMS: 30000,
connectTimeoutMS: 30000
}).then(() => {
console.log('Connected to MongoDB');
initDB();
}).catch(err => {
console.error('MongoDB connection error:', err.message);
});
// 访问记录 Schema
const VisitSchema = new mongoose.Schema({
count: { type: Number, default: 0 },
updatedAt: { type: Date, default: Date.now }
});
const Visit = mongoose.model('Visit', VisitSchema);
// 初始化数据库
async function initDB() {
const doc = await Visit.findOne();
if (!doc) {
await Visit.create({ count: 0 });
}
}
// 首页
app.get('/', async (req, res) => {
try {
await initDB();
const doc = await Visit.findOne();
doc.count += 1;
doc.updatedAt = new Date();
await doc.save();
res.send(`
<html>
<head><title>Node.js + MongoDB + Docker</title></head>
<body style="font-family: Arial; max-width: 600px; margin: 80px auto; text-align: center;">
<h1>🚀 Node.js + MongoDB + Docker Compose</h1>
<p>This page has been visited <strong>${doc.count}</strong> time(s).</p>
<p>Refresh the page to increment the counter.</p>
<hr>
<p style="color: gray;">Data is stored in MongoDB — survives container restart</p>
</body>
</html>
`);
} catch (e) {
res.send(`
<html>
<body style="font-family: Arial; max-width: 600px; margin: 80px auto; text-align: center;">
<h1>⚠️ Database not ready</h1>
<p>Waiting for MongoDB to start...</p>
<p style="color: gray;">Error: ${e.message}</p>
<p>Please refresh the page in a few seconds.</p>
</body>
</html>
`);
}
});
// API 端点
app.get('/api/visits', async (req, res) => {
const doc = await Visit.findOne();
res.json({ count: doc ? doc.count : 0 });
});
// 健康检查
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`);
});