当我尝试使用 docker-compose 运行 nodejs 的 docker 容器和 mysql 应用程序时出现端口使用错误

I get port in use error when I try to run the docker container for the nodejs and mysql application using the docker-compose

如何使用 docker-compose 创建容器并在启动时将参数传递给我的 Node.js 应用程序?

我正在尝试编写一个程序,我可以在其中使用 NODEJS 和 DOCKER-COMPOSE 连接 MYSQL。我需要 运行 终端中的应用程序,以便我可以在启动期间将一些参数传递给我的 Node.js 应用程序,因此我需要 运行 DOCKER-COMPOSE UP 到打开应用程序和 MYSQL 然后我想 运行 在另一个 window.

中使用 CLI 应用程序

这是我的 index.js 文件,存在于 web 文件夹中,当我 运行 使用以下命令 nodemon start New.[=36= 时,它将接受用户的输入]

     //Make NodeJS to Listen to a particular Port in Localhost
const   port        =   9010; 
     app.listen(port, function(){
        // Start the server and read the parameter passed by User
        console.log("Node js is Running on : "+port);
        // Get process.stdin as the standard input object.
        var standard_input = process.stdin;

        // Set input character encoding.
        standard_input.setEncoding('utf-8');

        // Prompt user to input data in console.
        console.log("Please input text in command line.");

        // When user input data and click enter key.
        standard_input.on('data', function (data) {
            console.log(" DATA ENTERED BY USER IS :"+data);
        });
    });

我想使用 docker-compose 实现此目的,因此我有以下 docker-compose.yml 文件的代码。

version: '3'

services:
  db:
    build: ./db
    environment:
      MYSQL_DATABASE: mydb
      MYSQL_ROOT_PASSWORD: mypass
      MYSQL_USER: mysql
      MYSQL_PASSWORD: mypass
      DATABASE_HOST: myhost
  web:
    build: ./web
    depends_on:
      - db
    restart: on-failure
    ports:
      - "9010:9010"

  adminer:
    image: adminer
    restart: always
    ports:
      - "7778:8080"

我的 Dockerfile 网络版或 web 文件夹中的 Node.js 是:

FROM node:8

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 9010

CMD ["npm","start"]

我的 Dockerfile 数据库 MYSQLdb 文件夹中是:

FROM mysql:5.7

EXPOSE 3306

COPY ./scripts /docker-entrypoint-initdb.d/

现在,当我 运行 命令 docker-compose up --build 用于 docker-compose.yml 文件时,一切正常;容器和 Node.js 应用程序启动。

当我打开另一个终端 window 并尝试使用 docker-compose exec web sh 导航到 web 容器并启动节点应用程序以传递参数 nodemon start New 然后我得到以下错误。

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::9010
    at Server.setupListenHandle [as _listen2] (net.js:1360:14)

因为当我 运行 命令 docker-compose up --build 端口已经分配时,Nodejs 应用程序已经 运行ning 了,所以我收到这个错误,我该如何启动 Indey.js 应用程序并向其传递参数?

我正在为应用程序使用 Ubuntu Os。

原因是已经有运行ning nodejs应用运行来自CMD并且占用了端口,所以当运行里面的命令docker 你得到 EDDRINUSE 错误。

您将有多种选择,

  • 不要从 docker 的 CMD 启动节点应用程序,但是当 nodejs 在容器内处理时,您不会注意到。 但这可以是处理的选项,所以在节点 Dockerfile
  • 中更改 CMD
CMD ["npm","start"]
#change the above cmd to
CMD tail -f /dev/null

这将只保留您的 nodejs 容器 运行ning,然后 运行 容器内的命令。

docker-compose exec web sh
nodemon start New
  • 手动更改您 运行 脚本的端口,这样就不会发生冲突,因为脚本将在不同的端口上启动,

稍微更新一下 nodejs 代码

//Make NodeJS to Listen to a particular Port in Localhost
const   port        =   process.env.PORT; 

现在用不同的端口启动进程

PORT=9011 nodemon start New