How to run commands out of docker container

Profile picture for user a.berramou
Azz-eddine BERRAMOU 12 March, 2021

It's annoying each time you need to run a command you should enter to the container before.

How to run commands without entering to your docker container ?

For exemple to run composer install in the normal case you need to run the following: 

$ docker exec -it docker-CONTAINER_NAME  /bin/bash
# Now you are inside container you can run 
$ composer install

So let's make life easy and change those two commandes by one alias:

  1. First thing we need is install this beautiful library smartcd and configure it like the following
    $ git clone https://github.com/cxreg/smartcd.git
    $ cd smartcd 
    $ make install
    $ source load_smartcd
    # Accept all with typing Y
    $ smartcd config
    
    
  2.  Second thing is to create necessary file to work with smartcd, in your project add the following files:
    for demonstration purposes i will create create some alias like composer and drush you can add as much as you want of alias in the same way.  
    .bash_enter file
    _alias_dc() { docker-compose $@;}
    _alias_run() { docker-compose run --rm $@;}
    _alias_php() { docker-compose run --rm --user YOUR_USER --workdir=/WORKDIR_PATH CONTAINER_NAME php $@;}
    _alias_composer() { docker-compose run --rm --user YOUR_USER --workdir=/WORKDIR_PATH CONTAINER_NAME composer $@;}
    _alias_drush() { docker-compose run --rm --user YOUR_USER --workdir=/WORKDIR_PATH CONTAINER_NAME vendor/drush/drush/drush $@;}
    
    ALIAS_FUNCTIONS=(_alias_dc _alias_run _alias_php _alias_composer _alias_drush)
    
    if [ -z "$BASH_ENTER_ALIAS_ONLY" ]; then echo "Commands: "; fi
    
    for func in $ALIAS_FUNCTIONS
    do
      autostash alias $(sed -r 's/^_?alias_//' <<< "${func}")="${func}"
      if [ -z "$BASH_ENTER_ALIAS_ONLY" ]; then echo " - $(sed -r 's/^_?alias_//' <<< "$func")"; fi
    done
    


    .bash_leave file

    ALIAS_FUNCTIONS=$(declare -F | sed -r 's/^declare -f //' | awk -F= '/^_?alias_/{print $1 }')
    for func in $ALIAS_FUNCTIONS
       do unset -f $func
    done
  3. Now all you need to do is open your terminal and go to your project root folder you will find all the alias declared in the .bash_enter file ready to go. 
    now you can run composer install without entering to container.

For more information read about smartcd here https://github.com/cxreg/smartcd especially the part of HOW DOES IT WORK?

You may also like