Nowadays cloud computing is being highly considered by many of researchers, organizations, governments and so on. According to processing happening inside of cloud computing, some of the most important problems and challenges in cloud computing are load balancing, managing resource allocations, scheduling running of tasks. Load balancing on the surface of virtual machines on the internal surface of datacenters, scheduling and resource allocations in hosts and over virtual machines. Thus, by considering existing challenges in cloud computing, in this paper by the help of dragonfly optimization algorithm because of speed and preciseness in scheduling tasks, the process of allocating resources to virtual machines in cloud computing has been done. The proposed method has multiple steps that are as follows: initialization of algorithm and cloud computing, setting number of virtual machines and tasks, running dragonfly optimization algorithm, allocating resources and scheduling tasks with maintaining load balance in virtual machines. By simulation of the proposed method in this research, we observed that the rate of improvement in dragonfly optimization algorithm for resource allocation and keeping load balance between virtual machines is much higher than other methods when considering criterions like execution time, response time, number of migrated tasks and load balance.