How to seed a docker container in Windows

风流意气都作罢 提交于 2019-12-11 08:36:05

问题


I intended to install a mongodb docker container from Docker Hub, and then insert some data into it. Obviously, a mongodb seed container is needed. So I did the following:

  1. created a Dockerfile of Mongo seed container in mongo_seed/Dockerfile and the code in Dockerfile is the following:

    FROM mongo:latest
    WORKDIR /tmp
    COPY data/shops.json .
    COPY import.sh .
    CMD ["/bin/bash", "-c", "source import.sh"]
    

    The code of import.sh is the following:

    #!/bin/bash
    ls .
    mongoimport --host mongodb --db data --collection shops --file shops.json
    

    the shops.json file contains the data to be imported to Mongo

  2. created a docker-compose.yml file in the current working directory, and the code is the following:

    version: '3.4'
    services:
      mongodb:
        image: mongo:latest
        ports: 
        - "27017:27017"
        container_name: mongodb 
      mongodb_seed:
        build: mongodb_seed
        links:
        - mongodb
    

The code above successfully made the mongodb service execute the import.sh to import the json data - shops.json. It works perfectly in my Ubuntu. However, when I tried to run command docker-compose up -d --build mongodb_seed in Windows, the import of data failed with errors logs:

Attaching to linux_mongodb_seed_1
mongodb_seed_1  | ls: cannot access '.'$'\r': No such file or directory
: no such file or directory2T08:33:45.552+0000  Failed: open shops.json
mongodb_seed_1  | 2019-04-02T08:33:45.552+0000  imported 0 documents

Anyone has any ideas why it was like that? and how to fix it so that it can work in Windows as well?


回答1:


Notice the error ls: cannot access '.'$'\r': No such file or directory.

One of the issues with Docker (or any Linux/macOS based system) on Windows is the difference in how line endings are handled.

Windows ends lines in a carriage return and a linefeed \r\n while Linux and macOS only use a linefeed \n. This becomes a problem when you try to create a file in Windows and run it on a Linux/macOS system, because those systems treat the \r as a piece of text rather than a newline.

Make sure to run dos2unix on script file whenever anyone edit anything on any kind of editor on Windows. Even if script file is being created on Git Bash don’t forget to run dos2unix

dos2unix import.sh

See https://willi.am/blog/2016/08/11/docker-for-windows-dealing-with-windows-line-endings/

In your case:

FROM mongo:latest
RUN apt-get update && apt-get install -y dos2unix
WORKDIR /tmp
COPY data/shops.json .
COPY import.sh .
RUN dos2unix /import.sh && apt-get --purge remove -y dos2unix
CMD ["/bin/bash", "-c", "source import.sh"]



回答2:


You can try to change line endings to UNIX in your script file.



来源:https://stackoverflow.com/questions/55470358/how-to-seed-a-docker-container-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!