Goowik
Goowik

Reputation: 803

Docker - failed to connect to running image

Before I start explaining my error, let me say I'm a Windows user and don't have a lot of experience using Unix commands. So each of these steps are done using the Docker Quickstart Terminal (MINGW64).

It was a few weeks ago I first heard about docker and thought using it for a node/express website. So I installed the Docker package on my Synology server.

After finishing up the website I've done the following:

  1. I followed the instructions on this website: https://docs.docker.com/windows/step_one/ Up until the last step, everything worked (including docker run hello-world)

  1. Then it was onto "Dockerizing a Node.js web app": https://docs.docker.com/engine/examples/nodejs_web_app/

File hierarchy:

src (C:.....\projectname)

--assets (folder)

--controllers (folder)

--public (folder)

--src (folder)

--util (folder)

--views (folder)

--node_modules (folder)

--bin (folder)

----www (file, no extention)

--app.js (file)

--Dockerfile (file, no extention)

--package.json (file)

As for content: www:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('projectname:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));

app.use(require('./controllers'));

};

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

package.json:

{
  "name": "projectname",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "bcrypt-nodejs": "0.0.3",
    "body-parser": "~1.13.2",
    "bookshelf": "^0.9.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "express-session": "^1.13.0",
    "i18n": "^0.8.0",
    "jade": "~1.11.0",
    "knex": "^0.10.0",
    "morgan": "~1.6.1",
    "mysql": "^2.10.2",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "serve-favicon": "~2.3.0"
  },
  "devDependencies": {
    "autoprefixer": "^6.3.3",
    "browserify": "^13.0.0",
    "connect-livereload": "^0.5.4",
    "grunt": "^0.4.5",
    "grunt-browserify": "^4.0.1",
    "grunt-contrib-cssmin": "^0.14.0",
    "grunt-contrib-sass": "^0.9.2",
    "grunt-contrib-uglify": "^0.11.1",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-postcss": "^0.7.2"
  }
}

So as you can see in the package.json and www (which was generated by the express generator command), I have to write npm start to run the node/express server.

Dockerfile:

FROM centos:centos6

RUN yum install -y epel-release
RUN yum install -y nodejs npm

COPY package.json /projectname/package.json
RUN cd /projectname; npm install --production

COPY . /projectname

EXPOSE 8080

CMD ["npm", "start"]

  1. After a successful build docker build -t username/projectname . I do get a SECURITY WARNING:

    Successfully built 5ed562273b56

    SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

Apart from that no errors are thrown, so I ran the image: docker run -p 49160:8080 -d username/projectname. After which I get a long hash string

de297db51ab6fb3f842abb58267c1e189d2b9de51715a619a2f5431e868dc54f


  1. Still following the principles on https://docs.docker.com/engine/examples/nodejs_web_app/. To test the image I listed the container id using docker ps which got me this:

CONTAINER ID | IMAGE | COMMAND | CREATED | STATUS | PORTS | NAMES

So completely empty! Nothing, except for the headers of the table... But when I use the code provided in the link and build their image it does give me a result (as stated in the article):

CONTAINER ID | IMAGE | COMMAND | CREATED | STATUS | PORTS | NAMES

26d3ac309d81 | username/centos-node-testing | "node /src/index.js" | 35 minutes ago | Up 35 minutes | 0.0.0.0:49160->8080/tcp | gigantic_ritchie


  1. Just to be sure, I tried calling the app using the curl-command: curl -i 192.168.99.100:49160. Unfortunately that gave me an error:

curl: (7) Failed to connect to 192.168.99.100 port 49160: Connection refused

The ip address is retrieved using the docker-machine ip command.


  1. As a last resort, someone suggested to simply run the app using following command docker run username/projectname. That however gave me an error:

    npm ERR! Error: ENOENT, open '/package.json'

    npm ERR! If you need help, you may report this log at:

    npm ERR! http://github.com/isaacs/npm/issues

    npm ERR! or email it to:

    npm ERR!

    npm ERR! System Linux 4.1.19-boot2docker

    npm ERR! command "node" "/usr/bin/npm" "start"

    npm ERR! cwd /

    npm ERR! node -v v0.10.42

    npm ERR! npm -v 1.3.6

    npm ERR! path /package.json

    npm ERR! code ENOENT

    npm ERR! errno 34

    npm ERR!

    npm ERR! Additional logging details can be found in:

    npm ERR! /npm-debug.log

    npm ERR! not ok code 0

Any ideas what might cause this?

Upvotes: 0

Views: 1945

Answers (1)

ThatsNinja
ThatsNinja

Reputation: 422

Your container is non-existent because the command you've provided (CMD, above) is returning a non-zero exit status, and the container is destroyed due to failure. In your Dockerfile, let's please try something like the following, which should ensure that npm start is run from within your project root:

FROM centos:centos6

RUN yum install -y epel-release
RUN yum install -y nodejs npm

COPY package.json /projectname/package.json

# Set the working directory 
WORKDIR /projectname

RUN npm install --production

COPY . /projectname

EXPOSE 8080

CMD ["npm", "start"]

Also, for future, you might have luck troubleshooting a container if you use docker run -it username/projectname /bin/bash.

Upvotes: 2

Related Questions