无法连接到Dockerized Express HTTPS服务器

时间:2019-03-08 00:40:43

标签: node.js docker express

我正在尝试通过HTTPS服务我的应用程序,以便可以将服务工作者与我的React应用程序一起使用。

为此,我在我的Express启动脚本中添加了https.createServer()

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('robotapp:server');
var http = require('http');
var fs = require('fs');
var https = require('https');

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

var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);
console.log('Listening on localhost:', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Add HTTPS server
 */

if (process.env.NODE_ENV === 'prod') {
    https
        .createServer(
            {
                key: fs.readFileSync('sslcerts/server.key', 'utf8'),
                cert: fs.readFileSync('sslcerts/server.pem', 'utf8')
            },
            app
        )
        .listen(443, function() {
            console.log('HTTPS listening on PORT 443');
        });
}

/**
 * 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);
}

当我构建Docker容器并启动应用程序时,HTTP和HTTPS服务器都会启动(我可以看到“在localhost:8000上监听”和“在PORT 443上监听HTTPS”消息)。我可以在PORT 8000上成功访问我的应用程序的HTTP版本,但是当我访问服务器上的PORT 443时,出现“无法访问此站点”错误。

起初我以为我可能将我的集装箱端口映射错了,但是我检查了一下,似乎没有异常之处

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                                          NAMES
16d0013eec8a        robotapp:2.1        "npm start"         4 seconds ago       Up 3 seconds        0.0.0.0:443->443/tcp, 0.0.0.0:8000->8000/tcp   silly_tesla

如果有人对我做错了什么建议,请告诉我:)

0 个答案:

没有答案