Nick
Nick

Reputation: 3090

Cloud9: Could not find an open port

I'm new to NodeJS and trying to set up an existing project (developed by someone else) in Cloud9 IDE (I'm using an older Cloud9 account; so not running on AWS). I've pulled the git and installed everything. This all seemed to go without problems.

To run the app locally, outside of Cloud9, you would start the server with npm run start (I know from the person who developed the app, this works for him). But I want to set it up in Cloud9, and in Cloud9 it is necessary to set some variables first (if I don't define the host first, it gives the error "Invalid Host header"). Therefore, I use the following two commands:

export HOST=$C9_HOSTNAME && export PORT=8080
npm run start

The npm run start produces the error:

Could not find an open port at appname-username.c9users.io.

Network error message: listen EADDRNOTAVAIL 35.189.252.103

I believe I have the port correct, considering https://docs.c9.io/docs/run-an-application. I’ve also tried the values 8081, 8082 and $PORT but none of these work.

Any ideas how I could get the Cloud9 local preview working?


Upon request some lines from start.js:

const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
console.log(`1. The host is ${HOST} on port ${DEFAULT_PORT}`);  //ADDED

choosePort(HOST, DEFAULT_PORT)
  .then(port => {
    console.log(`2. The host is ${HOST} on port ${DEFAULT_PORT}`);  //ADDED
    if (port == null) {
      // We have not found a port.
      return;
    }
    const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
    const appName = require(paths.appPackageJson).name;
    const urls = prepareUrls(protocol, HOST, port);
    // Create a webpack compiler that is configured with custom messages.
    const compiler = createCompiler(webpack, config, appName, urls, useYarn);
    // Load proxy config
    const proxySetting = require(paths.appPackageJson).proxy;
    const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
    // Serve webpack assets generated by the compiler over a web sever.
    const serverConfig = createDevServerConfig(
      proxyConfig,
      urls.lanUrlForConfig
    );
    const devServer = new WebpackDevServer(compiler, serverConfig);
    // Launch WebpackDevServer.
    devServer.listen(port, HOST, err => {
      if (err) {
        return console.log(err);
      }
      if (isInteractive) {
        clearConsole();
      }
      console.log(chalk.cyan('Starting the development server...\n'));
      openBrowser(urls.localUrlForBrowser);
    });

  })
  .catch(err => {
    if (err && err.message) {
      console.log(err.message);
    }
    process.exit(1);
  });

netstat --listen responds with the following information:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN     
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     1533837857 /home/ubuntu/.c9/6614254/collab.sock
unix  2      [ ACC ]     STREAM     LISTENING     1533835235 /home/ubuntu/.c9/bridge.socket
unix  2      [ ACC ]     STREAM     LISTENING     1533836998 /tmp/tmux-1000/cloud92.2

The function choosePort is part of the node module "react-dev-utils" and reads as follows:

function choosePort(host, defaultPort) {
  return detect(defaultPort, host).then(
    port => new Promise(resolve => {
      if (port === defaultPort) {
        return resolve(port);
      }
      if (isInteractive) {
        clearConsole();
        const existingProcess = getProcessForPort(defaultPort);
        const question = {
          type: 'confirm',
          name: 'shouldChangePort',
          message: chalk.yellow(
            `Something is already running on port ${defaultPort}.` +
              `${existingProcess ? ` Probably:\n  ${existingProcess}` : ''}`
          ) + '\n\nWould you like to run the app on another port instead?',
          default: true,
        };
        inquirer.prompt(question).then(answer => {
          if (answer.shouldChangePort) {
            resolve(port);
          } else {
            resolve(null);
          }
        });
      } else {
        console.log(
          chalk.red(`Something is already running on port ${defaultPort}.`)
        );
        resolve(null);
      }
    }),
    err => {
      throw new Error(
        chalk.red(`Could not find an open port at ${chalk.bold(host)}.`) +
          '\n' +
          ('Network error message: ' + err.message || err) +
          '\n'
      );
    }
  );
}

Upvotes: 3

Views: 5049

Answers (1)

willascend
willascend

Reputation: 1533

I did some googling on this and I think the issue might be with the host value you are setting. Per this Cloud9 support thread which references a similar error:

...You need to use 0.0.0.0 instead since c9user.io is the public address of the proxy. Or modify your /etc/hosts file. echo "0.0.0.0 $C9_HOSTNAME" | sudo tee -a /etc/hosts

So, try setting the host to 0.0.0.0 instead of the public hostname:

export HOST=0.0.0.0 && export PORT=8080 && npm run start

Also just found this on the support page you linked to:

If you're developing a server application, please note that you need to listen to 0.0.0.0 ($IP) and 8080 ($PORT). Listening to this port will enable your app to be viewable at http://-.c9users.io

Listening on 0.0.0.0 should resolve the issue.

Edit (in response to additional error being returned):

For the "Invalid host header" error, I think you're on the right track with setting disableHostCheck to true, but your npm script command isn't likely adhering to the flag from.the CLI. There are probably a few ways to get that flag passed, but the simplest might be to update your code to set the option when creating the dev server. Keep in mind this is just a quick fix to see if we can get it to work. It would be better to update the createDevServerConfig function to set the option:

const devServer = new WebpackDevServer(compiler, { ...serverConfig, disableHostCheck: true});

Another edit:

The disableHostCheck option is insecure and can open you up to vulnerabilities. It's considered a quick fix when testing locally and should only be used in a closed network. To fix the"Invalid host header" in an exposed environment, use the public option, where public is your DNS host name or public IP address:

const devServer = new WebpackDevServer(compiler, { ...serverConfig, public: process.env.PUBLIC_HOST }

You can then have this value passed in via the CLI environment like your other vars:

export HOST=0.0.0.0 && export PORT=8080 && export PUBLIC_HOST=$C9_HOSTNAME:8080 && npm run start

Disclaimer: I don't think the changes above are the best way to go about doing this (it would likely be better to update the createDevServerConfig function, but they should resolve your issues. More information on the disableHostCheck option can be found here, here, and here.

Upvotes: 5

Related Questions