I can't run rails console with Docker and Pass

2019-07-15 01:45发布

问题:

I've the next docker-compose container:

# docker-compose.yml
version: '2'
services:
 web:
  build: .
  ports:
    - "80:80"
  volumes:
    - .:/home/app/NAME_OF_MY_APP
 db:
  image: postgres:9.4
  ports:
    - "5432"
  environment:
    POSTGRES_USER: 'postgres'

I cannot figure out how can I run the rails console. I'm using the passenger/nginx image and everything is working. However, my DB is on another container and I'd like to entry at rails console to create manually a couple of users.

I tried with:

sudo docker-compose run web rails c

But it appears the next error:

ERROR: Cannot start service web: oci runtime error: exec: "rails": executable file not found in $PATH

Also, I tried:

sudo docker-compose run web "rails c"

But it stills showing the same output.

I'd like to entry at console, entry some users and store it on the postgres DB.

Thanks in advance!

回答1:

First you have to start your composed containers with docker-compose up, which starts all of your defined services. Then you can attach to your running containers by their name. You get the names of running containers from the output of docker ps, e.g.:

CONTAINER ID        IMAGE       COMMAND  CREATED        STATUS              PORTS                    NAMES
d6b317a4c10b        image       "..."    27 hours ago   Up 27 hours         0.0.0.0:4284->4284/tcp   container1
4fe15ab206b5        postgresql  "..."    27 hours ago   Up 27 hours         5432/tcp                 container2

So in this example container2 is my database. But I want to connect to my web application. So I can directly start a shell in the running container:

docker exec -it container1 bash

which starts a bash inside container1. From there you can run any command you like, e.g. your rails console.

Also you should use version 2 of docker-compose files, since version 1 lacks of some features.