我正在尝试将spring boot docker容器连接到mongodb docker容器。在开发Spring Boot应用程序时,我使用了一个MongoDB docker容器,端口27017映射到主机27017端口docker run -p 27017:27017 mongo:3.4
。开发完成后,我将spring应用程序容器化,但是容器化的spring app无法连接到mongodb容器。我知道问题是spring app正在localhost寻找mongodb。我的问题是我应该如何修改应用程序,以便不使用localhost来查找mongodb,而是使用mongodb容器的地址?
我的数据库连接使用以下类处理:
public class DB {
private final Datastore datastore;
private Morphia morphia;
/**
* Constructor for creating database instance
*/
public DB() {
morphia = new Morphia();
morphia.mapPackage("users");
datastore =
morphia.createDatastore(new MongoClient(), "test");
datastore.ensureIndexes();
}
/**
* Inserts given user to the database
*
* @param u a newly created user.
*/
public void addUser(User u) {
datastore.save(u);
}
/**
* Fetches and prints all documents in database
*
* @return json array of all documents in database
*/
public String getUsers() {
final Query<User> query = datastore.createQuery(User.class);
final List<User> employees = query.asList();
return objToJson(employees);
}
/**
* Returns the user with the specified ID.
*
* @param userID is the ID of the document in database
* @return document in json format
*/
public String getUser(ObjectId userID) {
final Query<User> query = datastore.createQuery(User.class)
.field("id").equal(userID);
final List<User> employees = query.asList();
return objToJson(employees);
}
/**
* Deletes the document with the given ID from database.
*
* @param userID is the ID of the document to be removed
*/
public void removeUser(ObjectId userID) {
final Query<User> query = datastore.createQuery(User.class)
.field("id").equal(userID);
datastore.delete(query);
}
/**
* Deletes all documents from database.
*/
public void removeUsers() {
final Query<User> query = datastore.createQuery(User.class);
datastore.delete(query);
}
/**
* Updates the fields of the document with given ID.
*
* @param userID is the ID of the document to be updated
* @param newUser contains the new fields
* @return results of the update in json format
*/
public String updateUser(ObjectId userID, User newUser) {
final Query<User> query = datastore.createQuery(User.class)
.field("id").equal(userID);
final UpdateOperations<User> updateOperations = datastore.createUpdateOperations(User.class);
if (newUser.getFirst_name() != null) {
String newName = newUser.getFirst_name();
updateOperations.set("first_name", newName);
}
if (newUser.getLast_name() != null) {
String newLastName = newUser.getLast_name();
updateOperations.set("last_name", newLastName);
}
if (newUser.getSalary() != 0) {
int newSalary = newUser.getSalary();
updateOperations.set("salary", newSalary);
}
final UpdateResults results = datastore.update(query, updateOperations);
return results.toString();
}
/**
* Translate object lists to the json array.
*
* @param query is the list of the user objects
* @return json array of the given users
*/
private String objToJson(List<User> query) {
List<String> attsToRemove = Arrays.asList(new String[]{"className"});
List<DBObject> dbObjList = new ArrayList<>(query.size());
DBObject dbObj;
for (Object obj : query) {
dbObj = morphia.toDBObject(obj);
for (int i = 0; i < attsToRemove.size(); i++) {
dbObj.removeField(attsToRemove.get(i));
}
dbObjList.add(dbObj);
}
String json = JSON.serialize(dbObjList);
return json;
}
这是我的弹簧启动控制器
@RestController
public class DemoController {
DB mongodb = new DB();
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "Greetings from Spring Boot";
}
@RequestMapping(value = "/users/{user_id}", method = RequestMethod.GET)
public String getUser(@PathVariable("user_id") ObjectId userID) {
return mongodb.getUser(userID);
}
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String getUsers() {
return mongodb.getUsers();
}
@RequestMapping(value = "/users", method = RequestMethod.POST)
public void createUser(@RequestBody User u) {
try {
mongodb.addUser(u);
} catch (Exception e) {
System.out.println(e.toString());
}
}
@RequestMapping(value = "/users", method = RequestMethod.DELETE)
public void deleteUsers() {
try {
mongodb.removeUsers();
} catch (Exception e) {
System.out.println(e.toString());
}
}
@RequestMapping(value = "/users/{user-id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable("user-id") ObjectId userID) {
try {
mongodb.removeUser(userID);
} catch (Exception e) {
System.out.println(e.toString());
}
}
@RequestMapping(value = "/users/{user-id}", method = RequestMethod.PUT)
public String updateUser(@PathVariable("user-id") ObjectId userID, @RequestBody User u) {
return mongodb.updateUser(userID, u);
}
这是我的Dockerfile:
FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD demo-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 27017
EXPOSE 8080
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
我阅读了here和here提到的解决方案。另外阅读几个教程,但我无法将任何这些解决方案都适用于我的代码。在我的代码中,我应该在哪里更改?
答案 0 :(得分:3)
主要问题是您的容器不在同一个网络中。我想你可以通过How to run Spring Boot and MongoDB in Docker containe找到一个有效的例子。这是一个简短的摘录:
docker network create spring_demo_net
创建网络docker run --name spring-demo-mongo --network=spring_demo_net -v /home/ubuntu/mongo-data:/data/db -d mongo
启动一个mongo容器spring.data.mongodb.uri=mongodb://spring-demo-mongo/YOUR_DB
spring-demo-mongo 是您在步骤1中创建的容器的名称。由于您没有使用SpringData存储库,因此无法使用,因此您需要通过显式传递主机和端口来创建MongoClient:
MongoClient mongoClient2 = new MongoClient("spring-demo-mongo", 27017);
docker build --tag=spring-demo-1.0
使用标记docker run -d --name spring-demo --network=spring_demo_net -p 8080:8080 spring-demo-1.0
启动您的码头图片