Home > database >  How do I run a post-boot script on a container in kubernetes
How do I run a post-boot script on a container in kubernetes

Time:11-10

I have in my application a shell that I need to execute once the container is started and that it remains in the background, I have seen using lifecycle but it does not work for me

 ports:
    - name: php-port
      containerPort: 9000
    lifecycle:
        postStart:
          exec:
            command: ["/bin/sh", "sh /root/script.sh"]

I need an artisan execution to stay in the background once the container is started

CodePudding user response:

You can try using something like supervisor

http://supervisord.org/

We use that to start the main process and a monitoring agent in the background so we get metrics out of it. supervisor would also ensure those processes stay up if they crash or terminate.

CodePudding user response:

When the lifecycle hooks (e.g. postStart) do not work for you, you could add another container to your pod, which runs parallel to your main container (sidecar pattern):

apiVersion: v1
kind: Pod
metadata:
  name: foo
spec:
  containers:
  - name: main
    image: some/image
    ...
  - name: sidecar
    image: another/container

If your 2nd container should only start after your main container started successfully, you need some kind of notification. This could be for example that the main container creates a file on a shared volume (e.g. an empty dir) for which the 2nd container waits until it starts it's main process. The docs have an example about a shared volume for two containers in the same pod. This obviously requires to add some additional logic to the main container.

apiVersion: v1
kind: Pod
metadata:
  name: foo
spec:
  volumes:
  - name: shared-data
    emptyDir: {}
  containers:
  - name: main
    image: some/image
    volumeMounts:
    - name: shared-data
      mountPath: /some/path
  - name: sidecar
    image: another/image
    volumeMounts:
    - name: shared-data
      mountPath: /trigger
    command: ["/bin/bash"]
    args: ["-c", "while [ ! -f /trigger/triggerfile ]; do sleep 1; done; ./your/2nd-app"]
  • Related