Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run command after container start up

I'm trying to execute command after docker container start.
Here is my Dockerfile

FROM mysite:myport/mongo:3.6
EXPOSE 27017
ADD mongo.js /data/mongodb/scripts/

here is my docker-compose.yml

mongo:
    image: test-mongo
    container_name: test-mongo
    hostname: mongo
    expose:
      - "27017"
    ports:
      - "27017:27017"
    command: mongo --eval load("/data/mongodb/scripts/mongo.js")   

docker-compose --no-ansi up returns me

Creating test-mongo ...
Creating test-mongo ... done
Attaching to test-mongo
test-mongo | MongoDB shell version v3.6.5
test-mongo | connecting to: mongodb://127.0.0.1:27017
test-mongo | 2018-06-09T15:46:50.229+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), rea
son: Connection refused
test-mongo | 2018-06-09T15:46:50.229+0000 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
test-mongo | connect@src/mongo/shell/mongo.js:251:13
test-mongo | @(connect):1:6
test-mongo | exception: connect failed
test-mongo exited with code 1

I don't uderstand how can I load my file after mongodb is started

like image 851
Victor Garbuz Avatar asked May 22 '26 16:05

Victor Garbuz


2 Answers

By passing a command in your docker-compose.yaml, you are overriding the normal behavior of the mongo image -- so the mongo server is never starting. The way you would typically handle this is to put your script into a second image, and then start a second container as part of your docker-compose.yaml that makes a network connection to the mongo server. Something like:

version: "3"

services:
  mongo:
    image: mongo

  client:
    image: my-mongo-client
    restart: on-failure
    command: mongo --host mongo --eval load("/data/mongodb/scripts/mongo.js")

The restart directive will cause the client container to restart automatically on failure, which is necessary because it may try to connect before the mongo server is available to handle connections.

like image 135
larsks Avatar answered May 25 '26 08:05

larsks


If all you're trying to do is initialize a new database, such as creating a new schema and adding a user, you can create an initialization script and load it into the container. From the Docker Hub documentation:

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

like image 26
Matt Avatar answered May 25 '26 07:05

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!