Write command args in kubernetes deployment

12/4/2020

Can anyone help with this, please?

I have a mongo pod assigned with its service. I need to execute some commands while starting the container in the pod.

I found a small examples like this:

command: ["printenv"]
    args: ["HOSTNAME", "KUBERNETES_PORT"]

But I want to execute these commands while starting the pod:

use ParkInDB
db.roles.insertMany( [ {name :"ROLE_USER"}, {name:"ROLE_MODERATOR"}, {name:"ROLE_ADMIN"} ])
-- benhsouna chaima
kubernetes
mongodb

3 Answers

12/4/2020

if you are looking forward to run the command before the container start or container stop you can use the container life cycle hooks.

https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/

however, if you can add a command in the shell script file and edit MongoDB image as per requirement

command:  ["/bin/sh", "-c", "/usr/src/script.sh"]

you also edit the yaml with

args:
  - '-c'
  - |
    ls
    rm -rf sql_scripts
    
-- Harsh Manvar
Source: StackOverflow

7/13/2021

When you use the official Mongo image, you can specify scripts to use on container startup. The answer accepted here provides you with some information on how this work.

Kubernetes

When it comes to Kubernetes, there are some pre-work you need to do.

What you can do is to write a script like my-script.sh that creates a userDB and insert an item into the users collection:

mongo userDB --eval 'db.users.insertOne({username: "admin", password: "12345"})'

and then write a Dockerfile based on the official mongo image, to copy your script into the folder where custom scripts are run on database initialization.

FROM mongo:latest

COPY my-script.sh /docker-entrypoint-initdb.d/

CMD ["mongod"]

Within the same directory containing your script and dockerfile, build the docker image with

docker build -t dockerhub-username/custom-mongo .

Push the image to docker hub or any repository of your choice, and use it in your deployment yaml.

deployment.yaml

...
spec:
  containers:
    - name: mongodb-standalone
      image: dockerhub-username/custom-mongo
      ports:
        - containerPort: 27017

Verify by going to your pod and check the logs. You will be able to see that mongo has initialized the db that you have specified in your script in the directory /docker-entrypoint-initdb.d/.

-- Max Lim
Source: StackOverflow

12/7/2020

you need to choice one solution :

1- use init-container to deployment for change and execute some command or file

2- use command and args in deployment yaml

for init-container visit this page and use.

for comnad and args use this model in your deployment yaml file:

- image:
  name:
  command: ["/bin/sh"]
  args: ["-c" , "PUT_YOUR_COMMAND_HERE"]
-- SAEED mohassel
Source: StackOverflow