Starting the Server

app.listen() binds your app to a port and begins accepting connections.

Syntaxapp.listen(port, callback)

Nothing happens until you call app.listen(). It tells Node.js to open a network port and hand incoming HTTP requests to Express.

The first argument is the port number. The optional callback runs once the server is ready, which is a good place to log a message.

Reading the port from the environment

In production the hosting platform usually tells you which port to use through an environment variable. A common pattern is process.env.PORT || 3000 so your app works both locally and in the cloud.

Example

Example · javascript
const express = require('express');
const app = express();

const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => res.send('Up and running'));

app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

When to use it

  • A production server calls app.listen() binding to 0.0.0.0 so it accepts connections on all network interfaces inside a Docker container.
  • A developer logs a startup message in the app.listen() callback to confirm the port is bound before running integration tests.
  • A graceful-shutdown implementation stores the returned server handle from app.listen() in order to call server.close() on SIGTERM.

More examples

Basic listen with callback

Calls app.listen() with a port and a callback that fires once the TCP socket is bound.

Example · js
const express = require('express');
const app = express();

app.get('/', (req, res) => res.send('Running!'));

app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});

Bind to all interfaces

Passes a hostname as the second argument to bind the server to all network interfaces, required inside Docker.

Example · js
const express = require('express');
const app = express();

app.get('/', (req, res) => res.send('OK'));

app.listen(3000, '0.0.0.0', () => {
  console.log('Listening on 0.0.0.0:3000 (all interfaces)');
});

Graceful shutdown with server handle

Stores the return value of app.listen() as a server handle to enable graceful shutdown on SIGTERM.

Example · js
const express = require('express');
const app = express();

app.get('/', (req, res) => res.send('OK'));

const server = app.listen(3000, () => console.log('Started'));

process.on('SIGTERM', () => {
  server.close(() => {
    console.log('Server closed gracefully');
    process.exit(0);
  });
});

Discussion

  • Be the first to comment on this lesson.