Search code examples
bashkubernetesbackground

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


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


Solution

  • 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"]