How do I get into a Docker container's shell?

ghz 8months ago ⋅ 72 views

I'm getting started working with Docker. I'm using the WordPress base image and docker-compose.

I'm trying to ssh into one of the containers to inspect the files/directories that were created during the initial build. I tried to run docker-compose run containername ls -la, but that didn't do anything. Even if it did, I'd rather have a console where I can traverse the directory structure, rather than run a single command. What is the right way to do this with Docker?

Answers

To get a console inside a Docker container where you can traverse the directory structure and inspect files, you can use the docker-compose exec command instead of docker-compose run.

Here's how you can do it:

docker-compose exec containername /bin/bash

Replace containername with the name of your container as defined in your docker-compose.yml file.

This command will start a bash session inside the specified container, allowing you to interactively explore the filesystem, execute commands, and inspect files as you would on a regular Linux system.

For WordPress specifically, your docker-compose.yml file might look something like this:

version: '3.7'

services:
  wordpress:
    image: wordpress:latest
    ports:
      - "8080:80"
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: exampleuser
      WORDPRESS_DB_PASSWORD: examplepass
      WORDPRESS_DB_NAME: exampledb
    volumes:
      - wordpress:/var/www/html

  db:
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: exampledb
      MYSQL_USER: exampleuser
      MYSQL_PASSWORD: examplepass
      MYSQL_RANDOM_ROOT_PASSWORD: '1'
    volumes:
      - db_data:/var/lib/mysql

volumes:
  wordpress:
  db_data:

In this case, if you want to enter the WordPress container, you would run:

docker-compose exec wordpress /bin/bash

Once inside the container, you can navigate the filesystem, inspect files, and perform any necessary debugging or maintenance tasks. When you're finished, simply exit the container by typing exit.