I am a little new to docker and I trying to figure out how to use docker compose. So far I have only created a test API called “http://localhost:3000/test” which would just return a “Hello World”. If i run my device using node index.js, the url would work completely find. However, the url would not work if I run using docker compose.
Here are the detailed code:
index.js:
app.get('/test', (req, res) => {
try {
res.status(200).send('Hello World');
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
backend.dockerfile:
FROM node:20
WORKDIR /app
COPY package*.json ./
RUN npm install && npm install -g nodemon
COPY . .
EXPOSE 3000
CMD ["node", "server/index.js"]
compose.yaml:
version: '3.9'
services:
backend:
container_name: backend
image: backend
build:
context: ./backend
dockerfile: backend.dockerfile
ports:
- 4000:4000
After running *docker compose build * and docker compose up:
docker compose up
time="2024-07-25T21:05:29-05:00" level=warning msg="C:\Users\...\...\...\compose.yaml: `version` is obsolete"
[+] Running 1/0
✔ Container backend Recreated 0.1s
Attaching to backend
backend | Server running on port 4000
Danh Nguyen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.