Home > Software engineering >  How to execute script by host after starting docker container
How to execute script by host after starting docker container

Time:03-22

I have docker-compose.yml file and I start a container with DB via docker-compose up -d db command.

I need to execute script by host machine that, briefly speaking, export dump to db in container.

So, now it looks like:

docker-compose up -d db
./script.sh

But I want to combine these two commands into one. My question is "Is it possible?"

I found out that Docker Compose doesn't support this feature. I know that I can create another script with these commands in it, but I want to leave only docker-compose up -d db

UPD: I would like to mention that I am using mcr.microsoft.com/mssql/server:2017-latest image

Also, have to say one more time that I need to execute script exactly on host machine

CodePudding user response:

You can't use the Docker tools to execute commands on the host system. A general design point around Docker is that containers shouldn't be able to affect the host.

Nothing stops you from writing your own shell script that runs on the host and does the steps you need:

#!/bin/sh
docker-compose -d up
./wait-for.sh localhost 1433
./script.sh

(The wait-for.sh script is the same as described in the answers to Docker Compose wait for container X before starting Y that don't depend on Docker health checks.)

For your use case it may be possible to run the data importer in a separate container. A typical setup could look like this; note that the importer will run every time you run docker-compose up. You may want to actually build this into a separate image.

version: '3.8'
services:
  db: { same: as you have currently }
  importer:
    image: mcr.microsoft.com/mssql/server:2017-latest
    entrypoint: ./wait-for.sh db 1433 -- ./script.sh
    workdir: /import
    volumes: [.:/import]

The open-source database containers also generally support putting scripts in /docker-entrypoint-initdb.d that get executed the first time the container is launched, but the SQL Server image doesn't seem to support this; questions like How can I restore an SQL Server database when starting the Docker container? have a complicated setup to replicate this behavior.

  • Related