Running redis on nodejs Docker image

2019-03-31 18:24发布

I have a Docker image which is a node.js application. The app retrieves some configuration info from Redis which is running locally. Because of that, I am trying to install Redis when Running my Docker image.

Is it possible to setup Redis by extending the Dockerfile of the node.js App?

If the solution is not through Dockerfile, how else can I achieve this?

As of now, the Dockerfile is as below:

FROM node:carbon

WORKDIR /app

COPY package.json /app

RUN npm install

COPY . /app

EXPOSE 3011

CMD node /app/src/server.js

1条回答
Juvenile、少年°
2楼-- · 2019-03-31 18:54

The best solution would be to use docker compose. With this you would create a redis container, link to it then start your node.js app. First thing would be to install docker compose detailed here - (https://docs.docker.com/compose/install/).

Once you have it up and running, You should create a docker-compose.yml in the same folder as your app's dockerfile. It should contain the following

version: '3'
services:
  myapp:
    build: .  
    ports:
     - "3011:3011"
    links:
     - redis:redis
  redis:
    image: "redis:alpine"

Then redis will be accessible from your node.js app but instead of localhost:6379 you would use redis:6379 to access the redis instance.

To start your app you would run docker-compose up, in your terminal. Best practice would be to use a network instead of links but this was made for simplicity.

This can also be done as desired, having both redis and node.js on the same image, the following Dockerfile should work, it is based off what is in the question:

FROM node:carbon

RUN wget http://download.redis.io/redis-stable.tar.gz && \
    tar xvzf redis-stable.tar.gz && \
    cd redis-stable && \
    make && \
    mv src/redis-server /usr/bin/ && \
    cd .. && \
    rm -r redis-stable && \
    npm install -g concurrently   

EXPOSE 6379

WORKDIR /app

COPY package.json /app

RUN npm install

COPY . /app

EXPOSE 3011

EXPOSE 6379

CMD concurrently "/usr/bin/redis-server --bind '0.0.0.0'" "sleep 5s; node /app/src/server.js" 

This second method is really bad practice and I have used concurrently instead of supervisor or similar tool for simplicity. The sleep in the CMD is to allow redis to start before the app is actually launched, you should adjust it to what suits you best. Hope this helps and that you use the first method as it is much better practice

查看更多
登录 后发表回答