Search code examples
dockeramazon-ec2docker-composesudostrongbox

Run sudo commands from inside of docker compose


I am using AWS EC2 instance and have installed docker and docker-compose on AWS linux.

Now I have a docker-compose.yml file which is trying the command mkdir -p /workspace/.m2/repositories. Now this command requires sudo, otherwise it gives permissions error.

I tried adding sudo inside docker-compose but it gave me an error saying

sudo: command not found

I can run this command manually and can comment this command inside of docker-compose.yml file but I am interested to know that is there any way to run this command from inside of docker-compose.yml file?


Solution

  • I may have a solution for you. You can extend the strongbox image in a custom Dockerfile to solve this issue I think.

    Create a new Dockerfile, like this one:

    Dockerfile

    FROM strongboxci/alpine:jdk8-mvn-3.5
    
    USER root
    
    RUN mkdir -p /workspace/.m2/repositories
    RUN chown jenkins:jenkins /workspace/.m2/repositories
    
    USER jenkins
    

    Then build the image with something like this:

    docker build -t mystrongbox:01 .
    

    And finally update the docker-compose.yml file to this:

    docker-compose.yml

    version: '2'
    services:
      strongbox-from-web-core:
        image: mystrongbox:01
        command:
          - /bin/bash
          - -c
          - |
             echo ""
             echo "[NOTICE]   This will take at least 2 to 5 minutes to start depending on your machine and connection!"
             echo ""
             echo "           Open http://localhost:48080/storages to browse the repository contents."
             echo ""
             sleep 5
             mkdir -p /workspace/.m2/repositories
             mvn clean install -DskipTests -Dmaven.repo.local=/workspace/.m2/repositories
             cd strongbox-web-core
             mvn spring-boot:run -Dmaven.repo.local=/workspace/.m2/repositories
        ports:
          - 48080:48080
        volumes:
          - ./:/workspace
        working_dir: /workspace
    

    Finally try again with:

    docker-compose up
    

    Then you will have the directory created in the image already, and ownership set to the jenkins user.