我是一个低端的前端开发人员,试图通过后端技能进行改进,为此,我已经在nodejs中编写了我的API,并且正在使用GitLab,AWS EC2,docker和pm2服务后端。

我几乎在GitLab中使用了基本的CI/CD设置,但是我遇到了一个问题,就是我的docker容器似乎在运行pm2时立即退出,而且我不知道如何使其持久化。你能帮我吗?

我非常简单的docker-compose.yml看起来像这样:

version: '3.7'
services:
  api:
    image: some-repo/some-image:latest

我的.gitlab-c.yml看起来像这样:

image: docker:18.09.7

variables:
  DOCKER_REPO: some-repo
  IMAGE_BASE_NAME: some-image
  IMAGE: $DOCKER_REPO/$IMAGE_BASE_NAME:$CI_COMMIT_REF_SLUG

services:
  - docker:18.09.7-dind

before_script:
  - docker login -u "$DOCKER_REGISTRY_USER" -p "$DOCKER_REGISTRY_PASSWORD"

after_script:
  - docker logout

stages:
  - build
  - deploy

build:
  stage: build
  script:
    - docker build . -t $IMAGE -f $PWD/staging.Dockerfile
    - docker push $IMAGE
    - echo $PWD

deploy:
  stage: deploy
  variables:
    RELEASE_IMAGE: $DOCKER_REPO/$IMAGE_BASE_NAME:latest
  script:
    - docker pull $IMAGE
    - docker tag $IMAGE $IMAGE
    - docker push $IMAGE
    - docker tag $IMAGE $RELEASE_IMAGE
    - docker push $RELEASE_IMAGE
    - apk add openssh-client
    - mkdir -p ~/.ssh
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
    - chmod 600 $AWS_KEY
    - ssh-keyscan www.gitlab.com >> ~/.ssh/known_hosts
    - ssh -i $AWS_KEY $AWS_URL "cd /home/ubuntu"
    - ssh -i $AWS_KEY $AWS_URL "docker system prune -a -f"
    - ssh -i $AWS_KEY $AWS_URL "docker login -u $DOCKER_REGISTRY_USER -p $DOCKER_REGISTRY_PASSWORD"
    - ssh -i $AWS_KEY $AWS_URL "docker pull $RELEASE_IMAGE"
    - ssh -i $AWS_KEY $AWS_URL "/snap/bin/docker-compose stop"
    - ssh -i $AWS_KEY $AWS_URL "/snap/bin/docker-compose up -d"
    - ssh -i $AWS_KEY $AWS_URL "docker logout"

我的staging.Dockerfile看起来像这样:
FROM node:latest

LABEL author="Mark Norgate"

WORKDIR /var/www/api

ENV ENVIRONMENT_CONFIG=staging

COPY ./src ./src
COPY ./package.json ./package.json
COPY ./tsconfig.json ./tsconfig.json
COPY ./.pm2/staging/ecosystem.config.js ./ecosystem.config.js
COPY ./credentials/some-credentials.json ./some-credentials.json

RUN npm install
RUN npm install --global typescript
RUN tsc -p .
RUN npm install --global pm2

EXPOSE 3001
EXPOSE 3002
EXPOSE 27017

ENTRYPOINT ["pm2", "start", "/var/www/api/ecosystem.config.js"]

我的ecosystem.config.js看起来像这样:

module.exports = {
  apps : [{
    name: 'API',
    script: '/var/www/api/lib/server.js',
    env: {
      GOOGLE_APPLICATION_CREDENTIALS: '/var/www/api/some-credentials.json'
    }
  }]
};

现在看来这一切正常。除了我所说的,容器会在执行此pm2命令后立即退出。我以为这很简单,就像在分离模式下运行docker-compose up一样,但这没有帮助。

谁能发现我的错误/遗漏?

最佳答案

您可以尝试使用pm2-runtime而不是pm2来促进容器集成-docs are here

关于node.js - docker-compose和pm2 : container exiting immediately,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61103653/

10-12 23:47