简体   繁体   中英

Is it possible to run command npm test from docker-compose?

I would like to ask if it's possible to make a test after my application is running in docker-compose. What should I know to make this goal? Right now my application is running with separate mongodb but the problem is that I can't run "npm test" without changing my mongodb URL. I was thinking if it's possible to run docker-compose and when mongodb is running test also. Thank you so much for help!

version: "3"

services:
api:
container_name: shortster
build: .
ports:
  - "3000:3000"
links:
  - mongo
  - test
volumes:
  - .:/app/dist
mongo:
container_name: mongodb
image: mongo
ports:
  - "27017:27017"
logging:
  driver: none

test:
command: npm test

I've generally found it useful to use environment variables for configuration, but allow them to fall back to the value they would have in a typical developer environment.

var mongoUrl = process.env.MONGO_URL || 'http://localhost:27017/db';
mongoose.connect(mongoUrl, {useNewUrlParser: true});

Now in your host development environment, you can start the database dependencies in Docker if you need, and then run the tests:

docker-compose up -d mongo
npm run test
# start a development copy of the application with live reloading:
npm run start

Compose generally expects its "services" to be long-running containers. If you try to put a one-off task like a test runner as a "service", it will get re-run every time you re-run docker-compose up . Trying to run tests like this also will require building the test code and test libraries into your image, but you don't actually need them just to run the normal application.

This means you can reduce your Docker image only include the application code and the production dependencies, not development-only or test-only requirements. You can generally reduce the docker-compose.yml to just

version: "3.8"
services:
  api:
    build: .
    ports:
      - "3000:3000"
    environment:
      MONGODB_URL: mongo://mongo:27017/db
    depends_on:
      - mongo
  mongo:
    image: mongo
    ports:
      - "27017:27017"
    logging:
      driver: none

You don't need to overwrite the code in the image with volumes: , or manually specify container_name: . links: do nothing in modern Docker and you can similarly just drop them. Specifying depends_on: is helpful, but isn't a hard guarantee the database will be running before the application starts, so you may need to try a couple of times to connect.

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