首页 > 解决方案 > 在特殊端口上使用 MongoDB 的 devcontainers

问题描述

我正在尝试使用远程 - 容器扩展在 vscode 上运行我的项目(Nextjs - MongoDB)

但我找不到如何在 27017 以外的新端口上运行 mongo,这是预定义的默认连接端口。

阅读文档似乎我应该使用forwardPorts

我的 devcontainer.json

    {
    "name": "Node.js & Mongo DB",
    "dockerComposeFile": "docker-compose.yml",
    "service": "app",
    "workspaceFolder": "/workspace",

    // Set *default* container specific settings.json values on container create.
    "settings": {},

    // Add the IDs of extensions you want installed when the container is created.
    "extensions": [
        "dbaeumer.vscode-eslint",
        "mongodb.mongodb-vscode" 
    ],

    // Use 'forwardPorts' to make a list of ports inside the container available locally.
    "forwardPorts": [2000, 27017],

    // Use 'postCreateCommand' to run commands after the container is created.
    // "postCreateCommand": "yarn install",

    // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
    "remoteUser": "node"
}

我的 docker-compose.yml

    version: "3"

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        # [Choice] Node.js version: 16, 14, 12
        VARIANT: 14
        # On Linux, you may need to update USER_UID and USER_GID below if not your local UID is not 1000.
        USER_UID: 1000
        USER_GID: 1000

    volumes:
      - ..:/workspace:cached

    # Overrides default command so things don't shut down after the process ends.
    command: sleep infinity

    # Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function.
    network_mode: service:db

    # Uncomment the next line to use a non-root user for all processes.
    # user: node

    # Use "forwardPorts" in **devcontainer.json** to forward an app port locally.
    # (Adding the "ports" property to this file will not forward from a Codespace.)

  db:
    image: mongo:latest
    restart: unless-stopped
    volumes:
      - mongodb-data:/data/db

    # Uncomment to change startup options
    environment:
      MONGO_INITDB_ROOT_USERNAME:
      MONGO_INITDB_ROOT_PASSWORD:
      MONGO_INITDB_DATABASE: local

    # Add "forwardPorts": ["27017"] to **devcontainer.json** to forward MongoDB locally.
    # (Adding the "ports" property to this file will not forward from a Codespace.)

volumes:
  mongodb-data:

谁能帮忙?

标签: mongodbdockerdocker-composevscode-devcontainer

解决方案


portsdb部分下添加

db:
    image: mongo:latest
    restart: unless-stopped
    volumes:
      - mongodb-data:/data/db
    ports:
      - 27017:27020
    # Uncomment to change startup options
    environment:
      MONGO_INITDB_ROOT_USERNAME:
      MONGO_INITDB_ROOT_PASSWORD:
      MONGO_INITDB_DATABASE: local

    # Add "forwardPorts": ["27017"] to **devcontainer.json** to forward MongoDB locally.
    # (Adding the "ports" property to this file will not forward from a Codespace.)

volumes:
  mongodb-data:

推荐阅读