Skip to content

Commit 1c56493

Browse files
committed
perf: replace mongosh ping with Python script for lightweight healthcheck
1 parent b0cb09c commit 1c56493

3 files changed

Lines changed: 35 additions & 2 deletions

File tree

compose.yml

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,15 @@ name: stoat
33
services:
44
# MongoDB: Database
55
database:
6-
image: docker.io/mongo
6+
build:
7+
context: .
8+
dockerfile: mongo.Dockerfile
79
restart: always
810
volumes:
911
- ./data/db:/data/db
12+
- ./mongo_ping.py:/mongo_ping.py
1013
healthcheck:
11-
test: echo 'db.runCommand("ping").ok' | mongosh localhost:27017/test --quiet
14+
test: ["CMD", "python3", "/mongo_ping.py"]
1215
interval: 10s
1316
timeout: 10s
1417
retries: 5

mongo.Dockerfile

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
FROM docker.io/mongo:latest
2+
3+
# install Python3, pip, pymongo for low memory usage healthcheck
4+
RUN apt-get update && \
5+
apt-get install -y python3 python3-pip python3-pymongo && \
6+
rm -rf /var/lib/apt/lists/*

mongo_ping.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from pymongo import MongoClient
2+
from pymongo.errors import PyMongoError
3+
import sys
4+
import json
5+
6+
try:
7+
client = MongoClient(
8+
"mongodb://localhost:27017",
9+
connectTimeoutMS=3000,
10+
serverSelectionTimeoutMS=5000,
11+
socketTimeoutMS=5000,
12+
directConnection=True,
13+
)
14+
15+
client.admin.command("ping")
16+
print(json.dumps({"ok": 1}))
17+
sys.exit(0)
18+
19+
except PyMongoError as e:
20+
print(json.dumps({
21+
"ok": 0,
22+
"error": str(e)
23+
}, ensure_ascii=False), file=sys.stderr)
24+
sys.exit(1)

0 commit comments

Comments
 (0)