Home > Enterprise >  How to execute some task in background within a docker container
How to execute some task in background within a docker container

Time:09-21

I'm trying to perform some user operation(change admin-user), after Neo4j container boots up. But my background script doesn't wait for the neo4j to come up and dies before Neo4j comes online.

entrypoint.sh is something like

if [some condition]
    my_function &
fi

if [${cmd}" == "neo4j" ]; then
    exec neo4j console 
fi

helper_file.sh has my_function

function my_function {

    echo "Checking to see if Neo4j has started at http://${DB_HOST}:${DB_PORT}..."
    curl --retry-connrefused --retry 5 --retry-max-time 300  http://${DB_HOST}:${DB_PORT}
    if [ $? -ne 0 ]; then
       echo "Curl failed with error $?. Exiting.."
       return 1
    fi
    migrate_users <--- another function
}

the problem that I'm facing is Neo4j doesn't bootup till curl is doing the retries.

Tue Sep 20 12:46:35 UTC 2022 Checking to see if Neo4j has started at http://localhost:7474...
Tue Sep 20 12:46:35 UTC 2022   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Tue Sep 20 12:46:35 UTC 2022                                  Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
Tue Sep 20 12:46:35 UTC 2022 curl: (7) Failed to connect to localhost port 7474: Connection refused
Tue Sep 20 12:46:35 UTC 2022 Curl failed with error 0. Exiting..
user: vmanage; command: neo4j
Directories in use:

How can I ensure that migrate_users function gets called after Neo4j has come up online completely?

CodePudding user response:

You can add a loop inside your script to check the health of neo4j container. If the health check get pass only proceeed further in you script otherwise loop untill it pass.

CodePudding user response:

Your function named my_function could use until to keep waiting for neo4j to start, for example:

function my_function {
    let RETRIES=0
    declare SUCCESS=0
    until [[ $SUCCESS -eq 1 ]] || [[ $RETRIES -eq 50 ]]; do
      echo "Checking to see if Neo4j has started at 
      http://${DB_HOST}:${DB_PORT}..."
      STATUS_CODE$(curl -w %{http_code} -o /dev/null -s http://${DB_HOST}:${DB_PORT})
      if [ $STATUS_CODE -eq 200 ]; then
        echo "Neo4j is up and running" && SUCCESS=1 && exit 0
      else
        echo "Neo4j not ready" && let RETRIES =1 && sleep 10
      fi
    done
    migrate_users
}

CodePudding user response:

You can use docker-compose with the depends_on condition to do that. Even docker-compose documentation recommends to implement some kind of script to wait until the service is up. Take a look to the following links docker-compose and stackoverflow

But it could be something like:

version: "2"
services:
  neo4j-admin:
    build: .
    depends_on:
      - "neo4j"
    command: ["./wait-for-it.sh","--", "sh", "change_admin_passwd.sh"]
  neo4j:
    image: neo4j
  • Related