i m learning docker and try to make a server express. My server work locally but not with a container. Here my files et directory structure.
Directory Structure:
- my_project
|- app
| |- index.js
| |- ...
|
|- package.json
|
|- Dockerfile
package.json:
{
"name": "bottwitterjeuxconcour",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" : "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
My Dockerfile:
FROM node:19-alpine3.16
WORKDIR /app
COPY app/ .
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8080
CMD ["npm", "start"]
my index.js
import express from "express";
const port = 8080;
const app = express();
app.get("/", (req, res, next) => {
res.send('test serveur node sur docker');
});
app.listen(port, () => {
console.log(`http://localhost:${port}`);
});
I do the next cmd
docker build -t my-node-app .
docker run -p 8080:3000 my-node-app
And i got no result on localhost:3000 or 8080
when i do a : docker ps
i see my container working:
145c4d30dc78 my-node-app "docker-entrypoint.s…" 17 seconds ago Up 15 seconds 8080/tcp, 0.0.0.0:8080->3000/tcp reverent_goodall
I test if my port 8080 is listen with:
docker exec -it reverent_goodall /bin/sh
netstat -tulpn
and got this:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 :::8080 :::* LISTEN 18/node
I don't understand what don't work..
CodePudding user response:
docker run -p 8080:3000 my-node-app
binds port 3000
of your container to port 8080
of your host. However, your express app is listening on port 8080
and not on port 3000
. Therefore try -p 8080:8080
. If you expose the port of your container by using -p
, then you might also want to remove the EXPOSE 8080
from your Dockerfile.