简体   繁体   中英

How to create a mongo database per service with Docker

I am working towards having multiple services (NodeJS, Spring-boot) that each have their own MongoDB Database-server-per-service (eventually targeting GCP & K8s) so that I can keep the data separate. I will be using Docker compose to launch both the service and database together. However, when I run multiple services, naturally I get port collision. Here is a typical docker-compose file:

version: '3'

# Define the services/containers to be run
services:
  myapp: #name of your service
    build: ./ # specify the directory of the Dockerfile
    ports:
      - "3000:3000" #specify ports forwarding
    links:
      - database # link this service to the database service
    volumes:
      - .:/usr/src/app
    depends_on:
      - database

  database: # name of the service
    image: mongo # specify image to build container from
    volumes:
        - ./data:/data/db
    ports:
        - "27017:27017"

I am looking for an example of how to do this. My thinking is that each compose file will have it's own ports and each service will map to those ports internally?

You can make yaml for deployment and explain all your containers in one pod (a Pod is a group of containers). Your deployment may look like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: application-deployment
  labels:
    app: application
spec:
  selector:
    matchLabels:
      app: application
  template:
    metadata:
      labels:
        app: application
    spec:
      containers:
      - name: application
        image: application:version
        ports:
        - containerPort: 3000
      name: database
        image: database:version
        ports:
        - containerPort: 27017

It is just deployment inside your cluster. You need to expose it outside the cluster. I recommend you to use Ingress for that.

Here you will have the database inside the pod. Also you can create 2 deployments for database and your app in the same namespace.

Also, you need to build Docker images manually or use the CI tool for that. You can manage environments ( prod, pre-prod, dev, test ) by namespaces. One namespace for one environment will give you full isolation. Also, to manage all this, I recommend you to use tools like Helm or kops .

There are a lot of differences between Kubernetes and Docker-compose, but the main difference is design. In Kubernetes, you have more entities for each level of application, and you can manage them. In Docker-compose, you configure all as one service in one place and usually it is hard to manage some specific things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM