首先,感谢您阅读我的问题,并尝试帮助我并为我的英语道歉。

我正在尝试使用Express Server项目和Mongo运行Docker,但可以完美构建Dockerfile,但是我这样做:
docker logs -f name
并显示下一个错误:
/usr/local/bin/docker-entrypoint-sh line 340: exec: npm not found
而且,我认为mongodb无法运行

如果添加节点,为什么不能识别npm?
如何运行npm并启动mongo?
我正在使用Ubuntu 17.10

这是我的Dockerfile:

# Install Node
FROM node:latest

# Install Mongo
FROM mongo:4.0.0-xenial

# Author
MAINTAINER MachineGun

# Create user Ubuntu 17.10 (64 bits)
RUN adduser --disabled-login dockeruser

# Work Directory
WORKDIR /home/expressserver

# Copy express project to docker
COPY expressserver expressserver

# Defaul user
USER dockeruser

# Config cointainer PORT:
# MongoDB listening on port: 27017
# Server listening on port: 8080
EXPOSE 27017 8080

# Exec MongoDB
CMD [mongo]

# Exec server with custom npm start
CMD ["npm", "run", "start:dev"]

另外,在app.js中,我在下一个uri中使用 Mongoose :mongodb://localhost:27017/ExpressServer,可以吗?
mongoose.connection.openUri('mongodb://localhost:27017/ExpressServer', { useNewUrlParser: true }, (err, res) => {

    if (err) {
        console.log('Error: Database not running on port 27017: \x1b[31m%s\x1b[0m', 'offline');
        // console.log('throw err: ', err);
        throw err;
    }
    console.log('Database running on port 27017: \x1b[32m%s\x1b[0m', 'online');
});

最佳答案

我已经解决了问题:D
非常感谢:D

最后我用了docker compose ...

这是我的docker-compose.yml:

version: '2'

services:
  server:
    container_name: expressserver
    build: ./
    ports:
      - "8080:8080"
    links:
      - mongo

  mongo:
    container_name: mongoDB
    image: mongo:latest
    volumes:
      - /var/lib/mongodb:/data/db
    ports:
      - "27017:27017"
    command: mongod --port 27017

这是我的Dockerfile:
FROM node:carbon

MAINTAINER MachineGun

RUN adduser --disabled-login dockeruser

WORKDIR /home/dockeruser

COPY expressserver expressserver

WORKDIR /home/dockeruser/expressserver

RUN npm install

USER dockeruser

EXPOSE 8080 27017
CMD ["npm", "start"]

并在我的app.js中与 Mongoose 连接:
const options = {
    autoIndex: false, // Don't build indexes
    reconnectTries: 30, // Retry up to 30 times
    reconnectInterval: 500, // Reconnect every 500ms
    poolSize: 10, // Maintain up to 10 socket connections
    // If not connected, return errors immediately rather than waiting for reconnect
    bufferMaxEntries: 0
 };


// Database connection
const connectWithRetry = () => {
    mongoose.connect("mongodb://mongo/expressdb", options)
    .then(()=>{
        console.log('Database running on port 27017: \x1b[32m%s\x1b[0m', 'online')
    })
    .catch( (err) => {
        console.log('MongoDB connection unsuccessful on port 27017: \x1b[31m%s\x1b[0m', 'offline');
        console.log('Retry after 5 seconds.');
        setTimeout(connectWithRetry, 5000)
    });
}
connectWithRetry();

关于docker - 带有Mongo和Express的Docker,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51592866/

10-10 04:42