👉🏻 디렉토리 구조 / directory structure
app.js (or server.js)
├─ db.js
├─ routes/
│ └─ index.js
│ └─ health.js
👉🏻 app.js
const express = require("express");
const app = express();
const port = 3000;
// 미들웨어 / middleware
app.use(express.json());
// 라우터 / router
const indexRouter = require("./routes/index");
app.use("/", indexRouter);
app.use("/health", require("./routes/health"));
app.listen(port, () => {
console.log(`Express server running on port ${port}`);
});
~
👉🏻 db.js
// db.js
const mysql = require("mysql2");
const db = mysql.createPool({
host: "host.docker.internal",
// host:"localhost",
user: "myapp",
password: "Myapp@1234",
database: "myapp",
port: 3306,
waitForConnections: true,
connectionLimit: 10,
connectTimeout: 10000,
});
module.exports = db;
👉🏻 routes/index.js
// routes/index.js
const express = require("express");
const router = express.Router();
const db = require("../db");
router.get("/", (req, res) => {
db.query("SELECT NOW() AS now", (err, results) => {
if (err) {
console.error(err);
return res.status(500).json({
success: false,
error: "Database connection failed",
});
}
res.json({
success: true,
message: "Connected to external MySQL!",
serverTime: results[0].now,
});
});
});
module.exports = router;
👉🏻 routes/health.js
const express = require("express");
const router = express.Router();
const db = require("../db");
router.get("/", (req, res) => {
db.query("SELECT 1", (err) => {
if (err) {
return res.status(500).json({ status: "DOWN" });
}
res.json({ status: "UP" });
});
});
module.exports = router;
👉🏻Dockerfile
FROM node:24
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node","app.js"]
👉🏻 이미지 빌드 / image build
sudo docker build -t myexpressapp .
⭐️이미지 및 컨테이너 확인 명령어 / Image and container verification commands
# 실행중인 컨테이너 확인 / Check running containers
sudo docker ps
# 모든 컨테이너 확인 / Check all containers
sudo docker ps -a
# 모든 이미지 확인 / Check all images
sudo docker images
# 컨테이너 삭제 / Delete container
sudo docker rm container name
# 이미지 삭제 / delete image
sudo docker rmi image name
👉🏻 컨테이너 실행 / Container run
sudo docker run --name yourexpressapp -d -p 8000:3000 --add-host=host.docker.internal:host-gateway myexpressapp
👉🏻브라우저 접속테스트 / Browser connection test
✔️ http://ipaddress:8000접속시 아래의 메세지가 출력되면 정상
If the message below is displayed when accessing http://ipaddress:8000, it is normal.
{"success":true,"message":"Connected to external MySQL!","serverTime":"2025-12-22T15:25:30.000Z"}
✔️ http://ipaddress:8000/health접속시 아래의 메세지가 출력되면 정상
If the message below is displayed when accessing http://ipaddress:8000/health, it is normal.
{"status":"UP"}
⭐️ 도커에 올리기 전에 테스트 하려면 db에서 host 수정하고 npm install로 mysql2와 express 모듈 설치 할것
To test before uploading to Docker, modify host in db and install mysql2 and express modules with npm install.