Search code examples
javascriptnode.jsdockerdocker-container

find docker name in a node.js application running inside docker container


I have a node.js application running inside a docker container with base image node:16-alpine3.11. I want to get the name of the container on which it is running on.

ex:
docker ps:

CONTAINER ID     NAMES
xyz               node

test.js:
const c_name= //get container name

Solution

  • From outside the container

    You can use the docker cli to do this. In the example we filter for ancestor bitnami/redis (in your case this would be node:16-alpine3.11)

    $ docker container ls --filter "ancestor=bitnami/redis" --format "table {{.ID}}\t{{.Image}}\t{{.Names}}"
    

    This returns the id, name and image of the container as a table. To retrieve the results as a json object, update the format flag like below:

    docker container ls --filter "ancestor=bitnami/redis" --format 'json { "Id":"{{.ID}}", "Image": "{{.Image}}", "Names": "{{.Names}}" }'
    

    See the handy cli reference docs provided by docker.

    From Inside the Container

    Pass the unix socket to the container and invoke a script to get the container name:

    $ docker run -it -v "/var/run/docker.sock:/var/run/docker.sock" origami-duckling:latest
    

    The Dockerfile for `origami-duckling looks like this:

    FROM node:16-alpine3.11
    
    WORKDIR /usr/app
    
    RUN apk add curl jq
    ENV DOCKER_HOST="unix:///run/docker.sock"
    
    COPY get-container-name.sh /usr/app/get-container-name.sh
    CMD /usr/app/get-name.sh
    

    You would probably run the get-container-name before you use cmd to run the node app in your container.

    The get-container-name.sh would look like this:

    #!/usr/bin/env sh
    export CONTAINER_NAME="$(curl -s --unix-socket /run/docker.sock http://docker/containers/$HOSTNAME/json | jq '.Name')"
    
    echo $CONTAINER_NAME
    

    Update: You can do this from within your node.js app if you need to:

    I'm using [email protected], got 12.x is pure ESM.

    const got = require('got');
    async function getHostName() {
      const metadata = await got(`http://unix:/var/run/docker.sock:/containers/${process.env.HOSTNAME}/json`).json();
    
      console.log('Container name', metadata.Name);
      return metadata.Name
    }