我正在尝试dockerize一个Node.js服务器。我使用以下index.js和Dockerfile文件:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
FROM node:latest
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm i
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
然后我运行docker build . -t webapp
和docker run -p 8080:3000 webapp
,但是当我尝试在浏览器中打开应用程序时,我看到"在http://localhost:8080/的网页可能暂时关闭,或者它可能已经永久移动到一个新的网址。">
然后,当我将index.js中的主机名更改为0.0.0.0
时,它似乎工作正常,我可以在http://localhost:8080/
下的浏览器中访问我的应用程序。
在本地主机和0.0.0.0
上的容器中运行应用程序有什么区别?
在容器中,localhost是容器本身。因此,当绑定到127.0.0.1时,程序将只接受来自容器内部的连接。
你需要绑定到0.0.0.0才能接受来自容器外部的连接。